[Tutor] subprocess module: when to _NOT_ use shell=True

akleider at sonic.net akleider at sonic.net
Sun Mar 10 17:56:26 CET 2013


I've not found anywhere a clear explanation of when not to set shell=True.
If the command line must be interpreted by the shell then clearly this
must be set. So the question that comes up is why not set it always?
In an effort to investigate, I came up with the following script that
indicates that the shell looks at only the first string in the array if
the first parameter is an array rather than a string. Switching between
cmd being a string vs an array and shell being set or not set gives 4
possibilities.
Any comments?

#!/usr/bin/env python

# file :  test.py (Python 2.7, NOT Python 3)
# Running on Linux platform (Ubuntu.)
print 'Running "tes.py"'

import subprocess

cmd = ["ls", "-l"]
# cmd = "ls -l"
p = subprocess.Popen(cmd,
                    # shell=True,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)
(s_out, s_err) = p.communicate()
print "Std_out returns:\n%s<end>\nStd_err returns:\n%s\n<end>"%\
          (s_out, s_err, )




More information about the Tutor mailing list