我可以使用执行终端命令os.system()
但我想捕获这个命令的输出。我怎样才能做到这一点?
>>> 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())
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)