Python 将 os.system 的输出分配给变量并防止其显示在屏幕上
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3503879/
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
Assign output of os.system to a variable and prevent it from being displayed on the screen
提问by John
I want to assign the output of a command I run using os.systemto a variable and prevent it from being output to the screen. But, in the below code ,the output is sent to the screen and the value printed for varis 0, which I guess signifies whether the command ran successfully or not. Is there any way to assign the command output to the variable and also stop it from being displayed on the screen?
我想将我运行的命令的输出分配os.system给一个变量,并防止它输出到屏幕上。但是,在下面的代码中,输出被发送到屏幕并且打印的var值为 0,我猜这表示命令是否成功运行。有没有办法将命令输出分配给变量并阻止它显示在屏幕上?
var = os.system("cat /etc/services")
print var #Prints 0
采纳答案by Chris Bunch
From "Equivalent of Bash Backticks in Python", which I asked a long time ago, what you may want to use is popen:
从我很久以前问过的“ Python 中的 Bash 反引号等效”中,您可能想要使用的是popen:
os.popen('cat /etc/services').read()
From the docs for Python 3.6,
This is implemented using subprocess.Popen; see that class's documentation for more powerful ways to manage and communicate with subprocesses.
这是使用 subprocess.Popen 实现的;有关管理和与子进程通信的更强大方法,请参阅该类的文档。
Here's the corresponding code for subprocess:
这是对应的代码subprocess:
import subprocess
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
回答by ianmclaury
The commands module is a reasonably high-level way to do this:
命令模块是执行此操作的合理高级方法:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
status is 0, output is the contents of /etc/services.
status 为 0,输出是 /etc/services 的内容。
回答by Walter Mundt
You might also want to look at the subprocessmodule, which was built to replace the whole family of Python popen-type calls.
您可能还想查看该subprocess模块,该模块旨在替换整个 Pythonpopen类型调用系列。
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
The advantage it has is that there is a ton of flexibility with how you invoke commands, where the standard in/out/error streams are connected, etc.
它的优点是在如何调用命令、连接标准输入/输出/错误流等方面具有很大的灵活性。
回答by Vasili Syrakis
I know this has already been answered, but I wanted to share a potentially better looking way to call Popen via the use of from x import xand functions:
我知道这已经得到了回答,但我想分享一种通过使用from x import x和函数调用 Popen 的可能更好看的方法:
from subprocess import PIPE, Popen
def cmdline(command):
process = Popen(
args=command,
stdout=PIPE,
shell=True
)
return process.communicate()[0]
print cmdline("cat /etc/services")
print cmdline('ls')
print cmdline('rpm -qa | grep "php"')
print cmdline('nslookup google.com')
回答by lexa-b
i do it with os.system temp file:
我用 os.system 临时文件来做:
import tempfile,os
def readcmd(cmd):
ftmp = tempfile.NamedTemporaryFile(suffix='.out', prefix='tmp', delete=False)
fpath = ftmp.name
if os.name=="nt":
fpath = fpath.replace("/","\") # forwin
ftmp.close()
os.system(cmd + " > " + fpath)
data = ""
with open(fpath, 'r') as file:
data = file.read()
file.close()
os.remove(fpath)
return data
回答by Chiel ten Brinke
For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcessobject, from which you can easily obtain the output as well as return code. Since you are only interested in the output, you can write a utility wrapper like this.
对于 python 3.5+,建议您使用subprocess 模块中的run 函数。这将返回一个CompletedProcess对象,您可以从中轻松获取输出和返回代码。由于您只对输出感兴趣,因此您可以编写这样的实用程序包装器。
from subprocess import PIPE, run
def out(command):
result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
return result.stdout
my_output = out("echo hello world")
# Or
my_output = out(["echo", "hello world"])
回答by Kearney Taaffe
Python 2.6 and 3 specifically say to avoid using PIPE for stdout and stderr.
Python 2.6 和 3 特别指出要避免将 PIPE 用于 stdout 和 stderr。
The correct way is
正确的方法是
import subprocess
# must create a file object to store the output. Here we are getting
# the ssid we are connected to
outfile = open('/tmp/ssid', 'w');
status = subprocess.Popen(["iwgetid"], bufsize=0, stdout=outfile)
outfile.close()
# now operate on the file

