[Python-checkins] cpython: Expand shlex.quote example (#9723)

eric.araujo python-checkins at python.org
Fri Jul 29 15:10:18 CEST 2011


http://hg.python.org/cpython/rev/43c41e19527a
changeset:   71595:43c41e19527a
parent:      71578:9538fc35ad55
user:        Éric Araujo <merwok at netwok.org>
date:        Fri Jul 29 15:08:42 2011 +0200
summary:
  Expand shlex.quote example (#9723)

files:
  Doc/library/shlex.rst |  27 ++++++++++++++++++++++-----
  1 files changed, 22 insertions(+), 5 deletions(-)


diff --git a/Doc/library/shlex.rst b/Doc/library/shlex.rst
--- a/Doc/library/shlex.rst
+++ b/Doc/library/shlex.rst
@@ -38,16 +38,33 @@
 .. 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.
 
-      >>> filename = 'somefile; rm -rf /home'
+   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::
+
       >>> 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:

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list