如何在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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 15:36:57  来源:igfitidea点击:

How can I get terminal output in python?

pythonterminal

提问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

You can use Popenin subprocessas they suggest.

您可以使用POPENsubprocess,他们建议。

with os, which is not recomment, it's like below:

with os,这不是推荐,如下所示:

import os
a  = os.popen('pwd').readlines()

回答by Mahmoud

The easiest way is to use the library commands

最简单的方法是使用库命令

import commands
print commands.getstatusoutput('echo "test" | wc')