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 开发者_如何学JAVAthe 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.
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.
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'
精彩评论