import subprocess >>> cmd = [ ‘echo’, ‘arg1’, ‘arg2’ ] >>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0] >>> print output arg1 arg2
>>>
使用subprocess.PIPE时存在错误。对于巨大的输出,请使用以下命令:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()