我想分配我使用os运行的命令的输出。系统的一个变量,并防止它被输出到屏幕。但是,在下面的代码中,输出被发送到屏幕,并且为var打印的值为0,我猜这表示命令是否成功运行。是否有办法将命令输出分配给变量并阻止它在屏幕上显示?

var = os.system("cat /etc/services")
print var #Prints 0

当前回答

从我很久以前问过的这个问题来看,你可能想用的是popen:

os.popen('cat /etc/services').read()

在Python 3.6的文档中,

这是使用subprocess.Popen实现的;看那个类 提供更强大的管理和通信方式的文档 子流程。


下面是子进程的对应代码:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print("program output:", out)

其他回答

您可能还想看看subprocess模块,构建该模块是为了取代整个Python popen类型调用家族。

import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)

它的优点是在如何调用命令方面有很大的灵活性,可以连接标准的in/out/error流等。

commands模块是一种相当高级的实现方式:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

状态为0,输出为/etc/services的内容

我知道这个问题已经被回答了,但我想分享一个可能更好看的方法来调用Popen,通过使用from x import x和函数:

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')

对于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"])

Python 2.6和3特别指出避免使用PIPE作为标准输出和标准错误。

正确的方法是

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