[Tutor] execute an OS command, get the output

Alan Gauld alan.gauld at freenet.co.uk
Sat Mar 11 10:06:10 CET 2006


> 1) the os.system module
> 2a-d) os.popen, and popen2 popen3 and popen4
> 3) the popen2 module
> 4) the subprocess module

Take a look at the OS topic in my tutorial. The process control section
covers all of these calls and explains their differences. It also points out
that the latter is intended to replace all the others and shows examples.

> #1 is synchronous, which is what I want, but it doesn't seem to have any
> means to capture stdout.

Actually they are all synchronous if the command is not interactive.
If the command requires input before it completes then it will wait
for Python to supply it if using popen (in the same way that it would
from a user if using system).

> #s 2-4 look like they support capturing stdout, but they seem to be
> asynchronous, which is at the very least overkill for me.

output = popen(command).read()

isn't too hard is it?

> More detail, in case it matters:  the command line I need to execute is
> actually three commands, with pipes between them, i.e.,
>
>  string xxxxxxx | grep zzzzzz | head -10

Just make sure its all within a string and Python doesn't care.
But in this case I'd use Pytthon to search for the string and get the
last 10 entries rather than grep/head...

Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list