简体   繁体   English

将 subprocess.Popen 调用的输出存储在字符串中

[英]Store output of subprocess.Popen call in a string

I'm trying to make a system call in Python and store the output to a string that I can manipulate in the Python program.我正在尝试在 Python 中进行系统调用并将输出存储到我可以在 Python 程序中操作的字符串中。

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

I've tried a few things including some of the suggestions here:我已经尝试了一些事情,包括这里的一些建议:

Retrieving the output of subprocess.call() 检索 subprocess.call() 的输出

but without any luck.但没有任何运气。

In Python 2.7 or Python 3在 Python 2.7 或 Python 3 中

Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string:您可以使用subprocess.check_output()函数将命令的输出存储在字符串中,而不是直接创建Popen对象:

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

In Python 2.4-2.6在 Python 2.4-2.6 中

Use the communicate method.使用communicate方法。

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

out is what you want. out就是你想要的。

Important note about the other answers关于其他答案的重要说明

Note how I passed in the command.注意我是如何传入命令的。 The "ntpq -p" example brings up another matter. "ntpq -p"示例提出了另一个问题。 Since Popen does not invoke the shell, you would use a list of the command and options— ["ntpq", "-p"] .由于Popen不调用 shell,因此您将使用命令和选项列表 — ["ntpq", "-p"]

This worked for me for redirecting stdout (stderr can be handled similarly):这对我重定向 stdout 有用(stderr 可以类似地处理):

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

If it doesn't work for you, please specify exactly the problem you're having.如果它不适合您,请准确说明您遇到的问题。

Python 2 : http://docs.python.org/2/library/subprocess.html#subprocess.Popen Python 2http : //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

In the Popen constructor, if shell is True , you should pass the command as a string rather than as a sequence.在 Popen 构造函数中,如果shellTrue ,则应该将命令作为字符串而不是序列传递。 Otherwise, just split the command into a list:否则,只需将命令拆分为一个列表:

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

If you need to read also the standard error, into the Popen initialization, you should set stderr to PIPE or STDOUT :如果您还需要读取标准错误,进入 Popen 初始化,您应该将stderr设置为PIPESTDOUT

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

NOTE: Starting from Python 2.7, you could/should take advantage of subprocess.check_output ( https://docs.python.org/2/library/subprocess.html#subprocess.check_output ).注意:从 Python 2.7 开始,您可以/应该利用subprocess.check_output ( https://docs.python.org/2/library/subprocess.html#subprocess.check_output )。


Python 3 : https://docs.python.org/3/library/subprocess.html#subprocess.Popen Python 3https : //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)

NOTE: If you're targeting only versions of Python higher or equal than 3.5, then you could/should take advantage of subprocess.run ( https://docs.python.org/3/library/subprocess.html#subprocess.run ).注意:如果您只针对高于或等于 3.5 的 Python 版本,那么您可以/应该利用subprocess.run ( https://docs.python.org/3/library/subprocess.html#subprocess.run )。

Assuming that pwd is just an example, this is how you can do it:假设pwd只是一个例子,你可以这样做:

import subprocess

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

See the subprocess documentation for another example and more information.有关另一个示例和更多信息,请参阅子流程文档

for Python 2.7+ the idiomatic answer is to use subprocess.check_output()对于 Python 2.7+,惯用的答案是使用 subprocess.check_output subprocess.check_output()

You should also note the handling of arguments when invoking a subprocess, as it can be a little confusing....您还应该注意调用子流程时对参数的处理,因为它可能有点令人困惑......

If args is just single command with no args of its own (or you have shell=True set), it can be a string.如果 args 只是一个没有自己的 args 的命令(或者你设置了shell=True ),它可以是一个字符串。 Otherwise it must be a list.否则它必须是一个列表。

for example... to invoke the ls command, this is fine:例如...调用ls命令,这很好:

from subprocess import check_call
check_call('ls')

so is this:这是这样的:

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

however, if you want to pass some args to the shell command, you can't do this:但是,如果您想将一些参数传递给 shell 命令,则不能这样做:

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

instead, you must pass it as a list:相反,您必须将其作为列表传递:

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

the shlex.split() function can sometimes be useful to split a string into shell-like syntax before creating a subprocesses... like this: shlex.split()函数有时可用于在创建子shlex.split()之前将字符串拆分为类似 shell 的语法......像这样:

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

In Python 3.7 + you can use the new capture_output= keyword argument for subprocess.run :Python 3.7 +您可以使用新的capture_output=关键字参数为subprocess.run

import subprocess

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

This works perfectly for me:这对我来说非常有效:

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 

This was perfect for me.这对我来说是完美的。 You will get the return code, stdout and stderr in a tuple.您将在元组中获得返回码、stdout 和 stderr。

from subprocess import Popen, PIPE

def console(cmd):
    p = Popen(cmd, shell=True, stdout=PIPE)
    out, err = p.communicate()
    return (p.returncode, out, err)

For Example:例如:

result = console('ls -l')
print 'returncode: %s' % result[0]
print 'output: %s' % result[1]
print 'error: %s' % result[2]

The accepted answer is still good, just a few remarks on newer features.接受的答案仍然很好,只是对新功能的一些评论。 Since python 3.6, you can handle encoding directly in check_output , see documentation .从 python 3.6 开始,您可以直接在check_output处理编码,请参阅文档 This returns a string object now:现在返回一个字符串对象:

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

In python 3.7, a parameter capture_output was added to subprocess.run(), which does some of the Popen/PIPE handling for us, see the python docs :在 python 3.7 中, capture_output () 中添加了一个参数capture_output ,它为我们做了一些 Popen/PIPE 处理,参见python 文档

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

I wrote a little function based on the other answers here:我根据这里的其他答案写了一个小函数:

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

Usage:用法:

changeset = pexec('hg','id','--id')
branch = pexec('hg','id','--branch')
revnum = pexec('hg','id','--num')
print('%s : %s (%s)' % (revnum, changeset, branch))
 import os   
 list = os.popen('pwd').read()

In this case you will only have one element in the list.在这种情况下,列表中将只有一个元素。

import subprocess
output = str(subprocess.Popen("ntpq -p",shell = True,stdout = subprocess.PIPE, 
stderr = subprocess.STDOUT).communicate()[0])

This is one line solution这是一行解决方案

The following captures stdout and stderr of the process in a single variable.以下在单个变量中捕获进程的 stdout 和 stderr。 It is Python 2 and 3 compatible:它与 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

If your command is a string rather than an array, prefix this with:如果您的命令是字符串而不是数组,请在其前面加上:

import shlex
command = shlex.split(command)

Use check_output method of subprocess module使用check_output的方法subprocess模块

import subprocess

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

Finally parse the string最后解析字符串

for line in res.splitlines():

Hope it helps, happy coding希望它有帮助,快乐编码

For python 3.5 I put up function based on previous answer.对于 python 3.5,我根据之前的答案设置了函数。 Log may be removed, thought it's nice to have日志可能会被删除,觉得很好

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM