Just augmenting @Kyle_Chase’s good suggestion. You could create a script in your project
script library called inetutils
:
import sys
import re
from subprocess import Popen, PIPE
def ping(host, count=1, timeout=1000):
if sys.platform == 'win32':
count_arg = '-n'
timeout_arg = '-w'
else:
count_arg = '-c'
timeout_arg = '-W'
args = map(str, [ 'ping', count_arg, count, timeout_arg, timeout, host ])
p = Popen(args, stdout=PIPE, stderr=PIPE)
output, err = p.communicate()
if p.returncode == 0: # success
try:
m = re.search("time=(\d+(?:\.\d+){0,1})\s*ms", output)
time = float(m.group(1))
except Exception, e:
time = -1
else:
time = None
return (time, p.returncode)
Then, in your project, you can use the something like the following:
from project.inetutils import ping
time, result = ping('google.com')
if result == 0:
print 'Success, response time is: %.2fms' % time
else:
print 'Failure, return code: %d' % result
The above solution will leverage the return code of the subprocess call, where 0 is a successful result. Other return codes will produce based on various failures of the call to ping such as 68
for unknown host, or 2
for response timeout. Keep in mind that this is still going to be a blocking call, so use accordingly.
Hope this helps!