Skip to content
Advertisement

Python Subprocess ping -h Returns Exit Status 2

I want to capture ping -h output using Python, it results in exit status 2.

I am working on a Linux host.

 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()

This is the output

`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.`

The command seems to execute normally on the shell. What is the cause of this error? How can I fix it?

Advertisement

Answer

Following Barmar solution

It is a normal behavior for ping, but the shell does not show it; Shell does not return exit status. We can see it by:

ping -h;echo $?

To avoid checking the exit status, we can replace subprocess.check_output() with subprocess.run()

and to capture the output successfully.

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

   print(res.stderr)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement