[Tutor] Correct way to call an outside program?

Kent Johnson kent37 at tds.net
Thu Mar 13 13:05:54 CET 2008


Allen Fowler wrote:
> Hello,
> 
> I need to call an external command line .exe utility from my Python script.
> 
> What is the best way to capture the output (if any) and (optionally) direct it to my normal standard output?

subprocess.Popen().communicate() will do it:

In [1]: import subprocess
In [7]: x=subprocess.Popen('ls', stdout=subprocess.PIPE, 
stderr=subprocess.PIPE).communicate()
In [10]: print x[0]
...

If you just want stdout and stderr of the subprocess to go to stdout and 
stderr of the calling process you can omit those arguments to Popen().

Kent


More information about the Tutor mailing list