0

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

5
  • 1
    Why are you running the command twice? Commented Jun 17, 2021 at 18:41
  • subprocess.check_output() raises an exception if the command has a non-zero exit status. And ping returns a non-zero status if it can't ping the IP. Commented Jun 17, 2021 at 18:43
  • I am making sure that it will run and it does. However it will not output the result. Commented Jun 17, 2021 at 18:45
  • It runs, but when the ping fails it returns a non-zero status. Commented Jun 17, 2021 at 18:45
  • Why are you passing the IP addresses as (weird) numbers instead of strings? I'd have thought that's a syntax error but not in a place where I can check. Commented Jun 17, 2021 at 18:53

1 Answer 1

1

subprocess.check_output() raises an exception if the command returns a non-zero exit status, and ping does this when it doesn't get a response to the pings.

Instead of using subprocess.call() and subprocess.check_output(), you should use subprocess.run().

command = ['ping', '-c', '1', '1.1.1.1']
print(subprocess.run(command, stdout=PIPE, stderr=STDOUT, encoding="utf-8").stdout)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.