subprocess module: execution of standard binaries without shell?

Chris Rebert clp2 at
Thu Feb 26 05:56:53 EST 2009

On Thu, Feb 26, 2009 at 2:41 AM, Visco Shaun <visco31 at> wrote:
> hi all
> while getting used to with subprocess module i failed in executuing a)
> but succeeded in running b). Can anyone explain me why as i am providing
> absolute path? Is this has to do anything with shared library.. which
> must be accessed based on system variables?
> a) pipe = subprocess.Popen("/bin/ls /", stdout=subprocess.PIPE,
> close_fds=True)
>                ==>OSError: [Errno 2] No such file or directory

You need to use a list of arguments, not just a string. You're
currently telling Python to try and run a nonexistent directory
(specifically, the "ls " subdirectory of /bin), since the string way
of calling Popen assumes that the *entire* string is the path to the
executable when shell=False.

The correct way is to provide the path to the binary and then each of
its arguments, in a list:
pipe = subprocess.Popen(["/bin/ls", "/"], stdout=subprocess.PIPE,

> b) pipe = subprocess.Popen("/bin/ls /", stdout=subprocess.PIPE,
> close_fds=True, shell=True)

This works because shell=True sends the string through the shell,
which tokenizes it and runs it, effectively splitting the string into
a list for you. However, shell=True is dangerous as you need to be
careful to escape special characters, whereas that's not necessary for
the 'shell=False and list' way of calling Popen.


Follow the path of the Iguana...

More information about the Python-list mailing list