【发布时间】:2021-05-01 22:29:58
【问题描述】:
我想使用 Python 捕获 ping -h 输出,它会导致退出状态 2。
我正在使用 Linux 主机。
import subprocess
class Network_Ping ():
def Get_Ping_Help(self):
res = subprocess.check_output(['ping', '-h'], universal_newlines = True)
print (res)
def main():
obj = Network_Ping()
obj.Get_Ping_Help()
if __name__ == "__main__":
main()
这是输出
`Traceback (most recent call last):
File "Network_Ping.py", line 42, in <module>
main()
File "Network_Ping.py", line 35, in main
obj.Get_Ping_Help()
File "Network_Ping.py", line 20, in Get_Ping_Help
res = subprocess.check_output(['ping', '-h'], universal_newlines = True)
File "/usr/lib/python3.8/subprocess.py", line 411, in check_output
return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
File "/usr/lib/python3.8/subprocess.py", line 512, in run
raise CalledProcessError(retcode, process.args,
subprocess.CalledProcessError: Command '['ping', '-h']' returned non-zero exit status 2.`
该命令似乎在 shell 上正常执行。这个错误的原因是什么?我该如何解决?
【问题讨论】:
-
这是正常的。运行
ping -h后,尝试在shell 中输入echo $?。 -
当程序返回非零退出状态时,shell 不会告诉你。
-
如果您不希望它检查退出状态,请使用
subprocess.run()。这就是名称中的check的意思。 -
@Barmar 谢谢。我以为
check_output是为了捕获shell 的输出。我已将其替换为subprocess.run(['ping', '-h'],capture_output=True, text = True)。 -
两者都有。
check表示检查退出状态,output表示捕获输出。
标签: python-3.x linux subprocess ping