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

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

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

检索subprocess.call()的输出

但运气不好。


当前回答

这对我来说非常合适:

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 

其他回答

下面将在单个变量中捕获流程的stdout和stderr。它兼容Python 2和3:

from subprocess import check_output, CalledProcessError, STDOUT

command = ["ls", "-l"]
try:
    output = check_output(command, stderr=STDOUT).decode()
    success = True 
except CalledProcessError as e:
    output = e.output.decode()
    success = False

如果你的命令是一个字符串而不是一个数组,用前缀this:

import shlex
command = shlex.split(command)

假设pwd只是一个例子,你可以这样做:

import subprocess

p = subprocess.Popen("pwd", stdout=subprocess.PIPE)
result = p.communicate()[0]
print result

有关另一个示例和更多信息,请参阅子流程文档。

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

这为我重定向stdout工作(stderr可以类似地处理):

from subprocess import Popen, PIPE
pipe = Popen(path, stdout=PIPE)
text = pipe.communicate()[0]

如果它不适合你,请具体说明你的问题。

对于Python 2.7+,惯用的答案是使用subprocess.check_output()

您还应该注意在调用子流程时对参数的处理,因为它可能有点令人困惑....

如果args只是一个单独的命令,没有自己的参数(或者你有shell=True set),它可以是一个字符串。否则它必须是一个列表。

例如……要调用ls命令,这是可以的:

from subprocess import check_call
check_call('ls')

这就是:

from subprocess import check_call
check_call(['ls',])

然而,如果你想传递一些参数给shell命令,你不能这样做:

from subprocess import check_call
check_call('ls -al')

相反,你必须将它作为一个列表传递:

from subprocess import check_call
check_call(['ls', '-al'])

shlex.split()函数有时可以在创建子进程之前将字符串分割成类似shell的语法…… 是这样的:

from subprocess import check_call
import shlex
check_call(shlex.split('ls -al'))