Paul Tarjan Paul Tarjan - 11 months ago 50
Python Question

Using python to run other programs

I have a command that works great on the command line. It has lots of arguments like

cmd --thing foo --stuff bar -a b input output

I want to run this from python and block waiting for it to complete. As the script prints things to
I want it to be immediately shown to the user.

What is the right module for this?

I've tried:

import commands
output = commands.getoutput("cmd --thing foo --stuff bar -a b input output")
print output

this works great except the
isn't returned until the end.

import os
os.system("cmd --thing foo --stuff bar -a b input output")

this prints all the output when the cmd is actually finished.

import subprocess["cmd", "--thing foo", "--stuff bar", "-a b", "input", "output"])

this doesn't pass the parameters correctly somehow (I haven't been able to find the exact problem, but
is rejecting my input). If I put
as the first parameter, it prints out the command which works perfectly when I paste it directly into the terminal.

import subprocess"cmd --thing foo --stuff bar -a b input output")

exactly the same as above.


If you don't need to process the output in your code, only to show it to the user as it happens (it's not clear from your Q, and it seems that way from your own self-answer), simplest is:

rc =
    ["cmd", "--thing", "foo", "--stuff", "bar", 
     "-a", "b", "input", "output"])
print "Return code was", rc

i.e., just avoid any use of pipes -- let stdout and stderr just show on the terminal. That should avoid any problem with buffering. Once you put pipes in the picture, buffering generally is a problem if you want to show output as it happens (I'm surprised your self-answer doesn't have that problem;-).

For both showing and capturing, BTW, I always recomment pexpect (and wexpect on Windows) exactly to work around the buffering issue.