subprocess question

Nobody nobody at nowhere.com
Mon Dec 12 10:16:58 EST 2011


On Sun, 11 Dec 2011 22:02:23 -0800, Chris Rebert wrote:

>>>>> p = subprocess.Popen(['du', '-sh'], cwd='/Users/jay/.Trash/', stdout=subprocess.PIPE)

> Alternatively, you can opt to use the shell by passing shell=True as
> an argument.

Except that the OP is talking about a directory passed to the cwd=
parameter, rather than as part of the command, and shell= doesn't affect
that.

But even if the directory was part of the command, just setting shell=True
won't work. On Unix (including MacOSX) the call:

	subprocess.Popen(['du', '-sh'], shell=True)

is equivalent to:

	subprocess.Popen(['/bin/sh', '-c', 'du', '-sh'], shell=False)

This will result in the shell executing "du" with no arguments. The
variable expansion "$1" will evaluate to "-sh", but that's meaningless as
"$1" doesn't occur in the argument to "-c".

The combination of using a list for the "args" parameter along
with shell=True is rarely useful on Unix. And using a string for the
"args" parameter introduces all of the associated reliability and security
issues.

The situation is different on Windows, where list/string and shell= are
orthogonal. A list is always converted to a string according to the
rules by which MSVCRT parses the command line into argv[]. Then, if
shell=True, "cmd.exe /c " is prepended to the string (actually, the value
of the COMSPEC environment variable is used in place of cmd.exe if it is
defined). Setting shell=True allows the "program" to be any file with a
registered extension, rather than just an executable.




More information about the Python-list mailing list