os.popen and the subprocess module

Nobody nobody at nowhere.com
Thu Nov 29 19:39:01 CET 2012

On Thu, 29 Nov 2012 10:09:44 +0100, Thomas Rachel wrote:

> The variant with shell=True is more os.popen()-like, but has security
> flaws (e.g., what happens if there are spaces or, even worse, ";"s in the
> command string?

I think that you're conflating the shell= option with whether the command
is a given as a list or a string.

Attempting to construct a command string risks introducing security flaws
(or other bugs). Wherever possible, the first argument should be a list. A
string should only be used if that's what you're given (e.g. via a
configuration file), in which case it should be used literally, without
any attempt to substitute filenames or other parameters.

On Windows, list-versus-string and shell= are orthogonal. A list will
always be converted to a string, as that's what the underlying
CreateProcess() function requires. shell=True prepends "cmd /c " ("cmd" is
replaced by the value of %comspec% if that is defined); this allows
execution of batch files, scripts, etc based upon their associations.

On Unix, passing a list with shell=True is rarely useful. It just prepends
['/bin/sh', '-c'] to the list, so the first item is the shell command
while subsequent items provide the values for the shell variables $1, $2,

More information about the Python-list mailing list