mirror of
https://github.com/python/cpython.git
synced 2025-10-28 09:10:36 +00:00
Add shlex.quote function, to escape filenames and command lines (#9723).
This function used to live as pipes.quote, where it was undocumented but used anyway. (An alias still exists for backward compatibility.) The tests have been moved as is, but the code of the function was changed to use a regex instead of a loop with string comparisons (at Ian Bicking’s suggestion). I’m terrible at regexes, so any feedback is welcome.
This commit is contained in:
parent
fcdaaa9011
commit
9bce311ea4
7 changed files with 66 additions and 42 deletions
|
|
@ -34,6 +34,22 @@ The :mod:`shlex` module defines the following functions:
|
|||
passing ``None`` for *s* will read the string to split from standard
|
||||
input.
|
||||
|
||||
|
||||
.. function:: quote(s)
|
||||
|
||||
Return a shell-escaped version of the string *s*. The returned value is a
|
||||
string that can safely be used as one token in a shell command line.
|
||||
Examples::
|
||||
|
||||
>>> filename = 'somefile; rm -rf /home'
|
||||
>>> command = 'ls -l {}'.format(quote(filename))
|
||||
>>> print(command)
|
||||
ls -l 'somefile; rm -rf /home'
|
||||
>>> remote_command = 'ssh home {}'.format(quote(command))
|
||||
>>> print(remote_command)
|
||||
ssh home 'ls -l '"'"'somefile; rm -rf /home'"'"''
|
||||
|
||||
|
||||
The :mod:`shlex` module defines the following class:
|
||||
|
||||
|
||||
|
|
@ -282,5 +298,4 @@ parsing rules.
|
|||
|
||||
* EOF is signaled with a :const:`None` value;
|
||||
|
||||
* Quoted empty strings (``''``) are allowed;
|
||||
|
||||
* Quoted empty strings (``''``) are allowed.
|
||||
|
|
|
|||
|
|
@ -92,7 +92,8 @@ This module defines one class called :class:`Popen`:
|
|||
>>> call("cat " + filename, shell=True) # Uh-oh. This will end badly...
|
||||
|
||||
*shell=False* does not suffer from this vulnerability; the above Note may be
|
||||
helpful in getting code using *shell=False* to work.
|
||||
helpful in getting code using *shell=False* to work. See also
|
||||
:func:`shlex.quote` for a function useful to quote filenames and commands.
|
||||
|
||||
On Windows: the :class:`Popen` class uses CreateProcess() to execute the
|
||||
child program, which operates on strings. If *args* is a sequence, it will
|
||||
|
|
@ -871,3 +872,7 @@ runtime):
|
|||
described in rule 3.
|
||||
|
||||
|
||||
.. seealso::
|
||||
|
||||
:mod:`shlex`
|
||||
Module which provides function to parse and escape command lines.
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue