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

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

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

检索subprocess.call()的输出

但运气不好。


当前回答

下面将在单个变量中捕获流程的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)

其他回答

这对我来说非常合适:

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.5,我根据前面的回答提出了函数。原木可能被移除,但它很好

import shlex
from subprocess import check_output, CalledProcessError, STDOUT


def cmdline(command):
    log("cmdline:{}".format(command))
    cmdArr = shlex.split(command)
    try:
        output = check_output(cmdArr,  stderr=STDOUT).decode()
        log("Success:{}".format(output))
    except (CalledProcessError) as e:
        output = e.output.decode()
        log("Fail:{}".format(output))
    except (Exception) as e:
        output = str(e);
        log("Fail:{}".format(e))
    return str(output)


def log(msg):
    msg = str(msg)
    d_date = datetime.datetime.now()
    now = str(d_date.strftime("%Y-%m-%d %H:%M:%S"))
    print(now + " " + msg)
    if ("LOG_FILE" in globals()):
        with open(LOG_FILE, "a") as myfile:
            myfile.write(now + " " + msg + "\n")

使用子进程模块的check_output方法

import subprocess

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

最后解析字符串

for line in res.splitlines():

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

 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