summaryrefslogtreecommitdiffstats
path: root/Doc/library/shlex.rst
diff options
context:
space:
mode:
authorÉric Araujo <merwok@netwok.org>2011-07-29 13:08:42 (GMT)
committerÉric Araujo <merwok@netwok.org>2011-07-29 13:08:42 (GMT)
commit30e277bf729f1b16d219195c651be3bd0ef8b5c1 (patch)
treec34a710b778282b3b88c34236858e38828ce298f /Doc/library/shlex.rst
parent8ef771f18f56fd3230d8c1b8d3c9ba98293e9174 (diff)
downloadcpython-30e277bf729f1b16d219195c651be3bd0ef8b5c1.zip
cpython-30e277bf729f1b16d219195c651be3bd0ef8b5c1.tar.gz
cpython-30e277bf729f1b16d219195c651be3bd0ef8b5c1.tar.bz2
Expand shlex.quote example (#9723)
Diffstat (limited to 'Doc/library/shlex.rst')
-rw-r--r--Doc/library/shlex.rst27
1 files changed, 22 insertions, 5 deletions
diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst
index e5aec4a..908f996 100644
--- a/Doc/library/shlex.rst
+++ b/Doc/library/shlex.rst
@@ -38,16 +38,33 @@ The :mod:`shlex` module defines the following functions:
.. 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::
+ string that can safely be used as one token in a shell command line, for
+ cases where you cannot use a list.
+
+ This idiom would be unsafe::
+
+ >>> filename = 'somefile; rm -rf ~'
+ >>> command = 'ls -l {}'.format(filename)
+ >>> print(command) # executed by a shell: boom!
+ ls -l somefile; rm -rf ~
+
+ :func:`quote` lets you plug the security hole::
- >>> filename = 'somefile; rm -rf /home'
>>> command = 'ls -l {}'.format(quote(filename))
>>> print(command)
- ls -l 'somefile; rm -rf /home'
+ ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print(remote_command)
- ssh home 'ls -l '"'"'somefile; rm -rf /home'"'"''
+ ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
+
+ The quoting is compatible with UNIX shells and with :func:`split`:
+
+ >>> remote_command = split(remote_command)
+ >>> remote_command
+ ['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
+ >>> command = split(remote_command[-1])
+ >>> command
+ ['ls', '-l', 'somefile; rm -rf ~']
The :mod:`shlex` module defines the following class: