Faulty returncode of subprocess.run()


import subprocess
import time
def ping(host):
    ping_cmd = ['ping', host]
    return subprocess.run(ping_cmd) == 0

online = True
while online:
    response = ping('google.com')

response should be True, but its False instead. it was working a week ago, am I missing something?

tried: response = not ping(‘google.com’) but if the server is offline it still equals True.

Asked By: Khacke



returns a CompletedProcess object, not the exit code directly.

To get the return code, you can do .returncode:

def ping(host):
    ping_cmd = ['ping', host]
    return subprocess.run(ping_cmd).returncode == 0

I’m not sure how it was working for you a week ago, but the documentation is what it is…

Also depending on your intended use case and platform, you may wish to limit the number of pings sent. Otherwise, your ping will run forever. You could use the -c flag to accomplish this:

def ping(host, count=1)
    ping_cmd = ['ping', '-c', str(count), host]

By default, this will send 1 ping packet.

Answered By: TrebledJ
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.