I am trying to use subprocess module in python to ping ip addresses. Here is the code.
command = ['ping', '-c', '1', 1.1.1.1]
print((subprocess.check_output(command)).decode("utf-8"))
This would return the proper ping result for 1.1.1.1.
Ping statistics for 1.1.1.1:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 4ms, Maximum = 4ms, Average = 4ms
However, if were to ping an invalid ip, like 0.0.0.0
command = ['ping', '-c', '1', 0.0.0.0]
subprocess.call(command)
print((subprocess.check_output(command)).decode("utf-8"))
Then subprocess.call(command) would return
Pinging 0.0.0.0 with 32 bytes of data:
PING: transmit failed. General failure.
Ping statistics for 0.0.0.0:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss)
However once the code reaches subprocess.check_output, it will not return anything and all subsequent code following it will not run. How can I have subprocess.check_output() return the full ping statement thrown by subprocess.call()?
subprocess.check_output()raises an exception if the command has a non-zero exit status. Andpingreturns a non-zero status if it can't ping the IP.