gpt4 book ai didi

python - 检查 CalledProcessError 的输出

转载 作者:IT老高 更新时间:2023-10-28 21:38:08 26 4
gpt4 key购买 nike

我正在使用 python 子进程模块中的 subprocess.check_output 来执行 ping 命令。这是我的做法:

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

它引发了一个 CalledProcessError 并说输出是函数的参数之一。谁能帮助我如何阅读该输出。我想将输出读入字符串并解析它。例如,如果 ping 返回

100% packet loss

我需要捕捉到这一点。如果还有其他更好的方法..请提出建议。谢谢。

最佳答案

根据Python os module documentation os.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.

如果您在 Python 2.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),

可以解析 e.output 字符串以满足 OP 的需求。

如果你想要返回码或其他属性,它们在 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']

关于python - 检查 CalledProcessError 的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7575284/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com