我试图在Python中进行系统调用,并将输出存储为我可以在Python程序中操作的字符串。

#!/usr/bin/python
import subprocess
p2 = subprocess.Popen("ntpq -p")

我尝试了一些事情,包括这里的一些建议:

检索subprocess.call()的输出

但运气不好。


当前回答

在Python 3.7+中,你可以为subprocess.run使用新的capture_output=关键字参数:

import subprocess

p = subprocess.run(["echo", "hello world!"], capture_output=True, text=True)
assert p.stdout == 'hello world!\n'

其他回答

我根据其他答案写了一个小函数:

def pexec(*args):
    return subprocess.Popen(args, stdout=subprocess.PIPE).communicate()[0].rstrip()

用法:

changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))

这对我来说非常合适:

import subprocess
try:
    #prints results and merges stdout and std
    result = subprocess.check_output("echo %USERNAME%", stderr=subprocess.STDOUT, shell=True)
    print result
    #causes error and merges stdout and stderr
    result = subprocess.check_output("copy testfds", stderr=subprocess.STDOUT, shell=True)
except subprocess.CalledProcessError, ex: # error code <> 0 
    print "--------error------"
    print ex.cmd
    print ex.message
    print ex.returncode
    print ex.output # contains stdout and stderr together 

在Python 3.7+中,你可以为subprocess.run使用新的capture_output=关键字参数:

import subprocess

p = subprocess.run(["echo", "hello world!"], capture_output=True, text=True)
assert p.stdout == 'hello world!\n'
import subprocess
output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE, 
stderr = subprocess.STDOUT).communicate()[0])

这是一条直线解

Python 2: http://docs.python.org/2/library/subprocess.html#subprocess.Popen

from subprocess import PIPE, Popen

command = "ntpq -p"
process = Popen(command, stdout=PIPE, stderr=None, shell=True)
output = process.communicate()[0]
print output

在Popen构造函数中,如果shell为True,则应该将命令作为字符串而不是序列传递。否则,只需将命令拆分为一个列表:

command = ["ntpq", "-p"]
process = Popen(command, stdout=PIPE, stderr=None)

如果你还需要读取标准错误到Popen初始化中,你应该将stderr设置为PIPE或STDOUT:

command = "ntpq -p"
process = subprocess.Popen(command, stdout=PIPE, stderr=PIPE, shell=True)
output, error = process.communicate()

注意:从Python 2.7开始,你可以/应该利用subprocess。# subprocess.check_output check_output (https://docs.python.org/2/library/subprocess.html)。


Python 3: https://docs.python.org/3/library/subprocess.html#subprocess.Popen

from subprocess import PIPE, Popen

command = "ntpq -p"
with Popen(command, stdout=PIPE, stderr=None, shell=True) as process:
    output = process.communicate()[0].decode("utf-8")
    print(output)

注意:如果你的目标只是Python版本高于或等于3.5,那么你可以/应该利用subprocess.run (https://docs.python.org/3/library/subprocess.html#subprocess.run)。