Waiting for a subprocess to exit

Miles Kaufmann milesck at umich.edu
Fri Aug 21 02:18:35 EDT 2009


On Aug 20, 2009, at 10:13 PM, Ben Finney wrote:
> The module documentation has a section on replacing ‘os.system’
> <http://docs.python.org/library/subprocess#replacing-os-system>, which
> says to use::
>
>    process = subprocess.Popen("mycmd" + " myarg", shell=True)
>    status = os.waitpid(process.pid, 0)
>
> But a ‘Popen’ instance has its own ‘wait’ method, which waits for exit
> <URL:http://docs.python.org/library/subprocess#subprocess.Popen.wait>.
> Why would I use ‘os.waitpid’ instead of::
>
>    process = subprocess.Popen("mycmd" + " myarg", shell=True)
>    process.wait()
>    status = process.returncode

Really, you can just use:

   process = subprocess.Popen("mycmd" + " myarg", shell=True)
   status = process.wait()

I'm not sure why the documentation suggests using os.waitpid.

I would recommend avoiding shell=True whenever possible.  It's used in  
the examples, I suspect, to ease the transition from the functions  
being replaced, but all it takes is for a filename or some other input  
to unexpectedly contain whitespace or a metacharacter and your script  
will stop working--or worse, do damage (cf. the iTunes 2 installer  
debacle[1]).  Leaving shell=False makes scripts more secure and  
robust; besides, when I'm putting together a command and its  
arguments, it's as convenient to build a list (['mycmd', 'myarg']) as  
it is a string (if not more so).

-Miles

[1]: http://apple.slashdot.org/article.pl?sid=01/11/04/0412209#comment_2518563


More information about the Python-list mailing list