【问题标题】:Python Subprocess ping -h Returns Exit Status 2Python 子进程 ping -h 返回退出状态 2
【发布时间】: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


【解决方案1】:

遵循 Barmar 解决方案

ping 是正常行为,但 shell 不显示; Shell 不返回退出状态。我们可以通过以下方式看到它:

ping -h;echo $?

为了避免检查退出状态,我们可以将subprocess.check_output()替换为subprocess.run()

并成功捕获输出。

   res = subprocess.run(['ping', '-h'],capture_output=True, text = True)

   print(res.stderr)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-17
    • 2020-10-24
    • 2012-04-21
    • 2014-09-23
    • 2015-03-11
    • 2017-03-19
    • 2010-10-28
    • 1970-01-01
    相关资源
    最近更新 更多