问题:将os.system的输出分配给变量,并防止其在屏幕上显示
我想将我使用的命令的输出分配给os.system变量,并防止将其输出到屏幕。但是,在下面的代码中,输出将发送到屏幕,并且打印的var值为0,我猜这表明命令是否成功运行。有什么方法可以将命令输出分配给变量,也可以阻止它在屏幕上显示?
var = os.system("cat /etc/services")
print var #Prints 0
回答 0
从我很久以前问过的“ Python中的Bash反引号等效 ”中,您可能想使用的是popen:
os.popen('cat /etc/services').read()这是使用subprocess.Popen实现的;有关更强大的方法来管理子流程和与子流程进行通信,请参见该类的文档。
这是对应的代码subprocess:
import subprocess
proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
回答 1
您可能还需要查看该subprocess模块,该模块是为替换整个Python popen类型调用系列而构建的。
import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)
它的优点是在调用命令,连接标准输入/输出/错误流等方面具有很大的灵活性。
回答 2
命令模块是执行此操作的合理的高级方法:
import commands
status, output = commands.getstatusoutput("cat /etc/services")
status为0,输出为/ etc / services的内容。
回答 3
对于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"])
回答 4
我知道已经解决了这个问题,但是我想分享一种通过使用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')
回答 5
我用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
回答 6
Python 2.6和3明确表示要避免将PIPE用于stdout和stderr。
正确的方法是
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
	声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

