How do I ping a website or IP address with Python?
Here's a short snippet using subprocess
. The check_call
method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using shlex
to split the command line arguments.
import subprocess
import shlex
command_line = "ping -c 1 www.google.comsldjkflksj"
args = shlex.split(command_line)
try:
subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
print "Website is there."
except subprocess.CalledProcessError:
print "Couldn't get a ping."