Python 子进程 ping -h Returns 退出状态 2
Python Subprocess ping -h Returns Exit Status 2
我想使用 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 上正常执行。这个错误的原因是什么?我该如何解决?
遵循 Barmar 解决方案
这是 ping 的正常行为,但 shell 没有显示; Shell 不 return 退出状态。我们可以通过:
ping -h;echo $?
为避免检查退出状态,我们可以将subprocess.check_output()
替换为subprocess.run()
并成功捕获输出。
res = subprocess.run(['ping', '-h'],capture_output=True, text = True)
print(res.stderr)
我想使用 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 上正常执行。这个错误的原因是什么?我该如何解决?
遵循 Barmar 解决方案
这是 ping 的正常行为,但 shell 没有显示; Shell 不 return 退出状态。我们可以通过:
ping -h;echo $?
为避免检查退出状态,我们可以将subprocess.check_output()
替换为subprocess.run()
并成功捕获输出。
res = subprocess.run(['ping', '-h'],capture_output=True, text = True)
print(res.stderr)