如何在python中获得终端输出?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4408377/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get terminal output in python?
提问by AssemblerGuy
I can execute a terminal command using os.system()but I want to capture the output of this command. How can I do this?
我可以使用执行终端命令,os.system()但我想捕获此命令的输出。我怎样才能做到这一点?
采纳答案by Ji?í Polcar
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
There is a bug in using of the subprocess.PIPE. For the huge output use this:
使用 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()
回答by Sven Marnach
The recommended way in Python starting from version 3.5 is to use subprocess.run():
从 3.5 版开始,Python 中的推荐方法是使用subprocess.run():
from subprocess import run
output = run("pwd", capture_output=True).stdout
Use the subprocessmoduleinstead.
改用subprocess模块。
from subprocess import Popen, PIPE
pipe = Popen("pwd", shell=True, stdout=PIPE).stdout
output = pipe.read()
回答by gerry
回答by Mahmoud
The easiest way is to use the library commands
最简单的方法是使用库命令
import commands
print commands.getstatusoutput('echo "test" | wc')

