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

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

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

检索subprocess.call()的输出

但运气不好。


当前回答

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

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))

其他回答

对于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")

对于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'))

在Python 2.7或Python 3中

不用直接创建Popen对象,你可以使用subprocess.check_output()函数将命令的输出存储在字符串中:

from subprocess import check_output
out = check_output(["ntpq", "-p"])

在Python 2.4-2.6中

使用沟通方法。

import subprocess
p = subprocess.Popen(["ntpq", "-p"], stdout=subprocess.PIPE)
out, err = p.communicate()

出去是你想要的。

关于其他答案的重要提示

注意我是如何传入命令的。“ntpq -p”示例引出了另一个问题。由于Popen不调用shell,因此可以使用命令和选项的列表- ["ntpq", "-p"]。

使用子进程模块的check_output方法

import subprocess

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

最后解析字符串

for line in res.splitlines():

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

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

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))