views:

70

answers:

2

I'm trying to use the subprocess module with Python 2.6 in order to run a command and get its output. The command is typically ran like this:

/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'

What's the best way to use the subprocess module in my script to execute that command with those arguments and get the return value from the command? I'm using Python 2.6.

+2  A: 

f.e. stdout you can get like this:

>>> import subprocess
>>> process = subprocess.Popen("echo 'test'", shell=True, stdout=subprocess.PIPE)
>>> process.wait()
0
>>> process.stdout.read()
'test\n'
Pydev UA
If you just want to check that the call succeeded (not what you're trying to do, but it's good to know) you can use subprocess.check_call() - this will raise an exception if the exit code is not 0.
Michael Richardson
+4  A: 

Do you want the output, the return value (AKA status code), or both?

If the amount of data emitted by the pipeline on stdout and/or stderr is not too large, it's pretty simple to get "all of the above":

import subprocess

s = """/usr/local/sbin/kamctl fifo profile_get_size myprofile | awk -F ':: ' '{print $2}'"""

p = subprocess.Popen(s, shell=True, stdout=subprocess.PIPE)

out, err = p.communicate()

print 'out: %r' % out
print 'err: %r' % err
print 'status: %r' % p.returncode

If you have to deal with potentially huge amounts of output, it takes a bit more code -- doesn't look like you should have that problem, judging from the pipeline in question.

Alex Martelli
Ok to ask why you're using shell=True here as well as subprocess.PIPE? thanks for the rest.
randombits
You need a shell to interpret and properly execute the pipes _inside_ the string; and you need `subprocess.PIPE` for the overall `stdout` of the string of commands (as executed by the shell) to come back to your Python program.
Alex Martelli