检查来自被叫进程的输出

2024-05-21 06:03:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用subprocess.check_pythons subprocess模块的输出来执行ping命令。我是这样做的:

output = subprocess.check_output(["ping","-c 2 -W 2","1.1.1.1")

它正在引发一个CalledProcessError,并表示输出是函数的参数之一。有谁能帮我读一下那个输出吗。我想把输出读入一个字符串并解析它。例如,如果ping返回

100% packet loss

我需要抓住它。如果还有其他更好的方法…请建议。谢谢。


Tags: 模块方法函数字符串命令output参数packet
3条回答

在参数列表中,每个条目必须独立。使用

output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])

应该能解决你的问题。

根据Python os module documentationos,popen从Python 2.6开始就被弃用了。

我认为现代Python的解决方案是使用来自subprocess模块的check_output()。

subprocess Python documentation

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) Run command with arguments and return its output as a byte string.

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

如果在Python2.7(或更高版本)中运行以下代码:

import subprocess

try:
    print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
    print "Ping stdout output:\n", e.output

您应该看到如下输出:

Ping stdout output:

Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.

Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),

输出字符串可以被解析以满足操作需要。

如果需要returncode或其他属性,则它们位于CalledProccessError中,这可以通过使用pdb单步执行来看到

(Pdb)!dir(e)   

['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
 '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
 '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
 '__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']

如果要将stdout和stderr取回(包括在发生stdout和stderr时从调用的进程中提取它),请使用以下命令:

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

这与Python2和3兼容。

如果命令是字符串而不是数组,请在其前面加上:

import shlex
command = shlex.split(command)

相关问题 更多 >