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

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

当前回答

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

其他回答

我用的是os。系统临时文件:

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

您可能还想看看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的内容

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

我知道这个问题已经被回答了,但我想分享一个可能更好看的方法来调用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')