我试图在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 

其他回答

 import os   
 list = os.popen('pwd').read()

在这种情况下,列表中只有一个元素。

公认的答案仍然很好,只是对更新的功能做了一些评论。从python 3.6开始,你可以直接在check_output中处理编码,参见文档。现在返回一个字符串对象:

import subprocess 
out = subprocess.check_output(["ls", "-l"], encoding="utf-8")

在python 3.7中,subprocess.run()中添加了一个参数capture_output,它为我们做了一些Popen/PIPE处理,请参阅python文档:

import subprocess 
p2 = subprocess.run(["ls", "-l"], capture_output=True, encoding="utf-8")
p2.stdout

使用子进程模块的check_output方法

import subprocess

address = '192.168.x.x'
res = subprocess.check_output(['ping', address, '-c', '3'])

最后解析字符串

for line in res.splitlines():

希望能有所帮助,编码愉快

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

import subprocess

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

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

这对我来说非常合适:

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