Design idea for Ping Application
Andrew Dalke
adalke at mindspring.com
Mon Aug 18 20:50:16 EDT 2003
Marc:
> I've been searching old posts for ideas, and can't quite come up with
> anything. In short I need an application that will continuously ping
> 11 different hosts and track the status of the pings.
That was a flashback. I posted a "sndping" module on this
list many years ago. It made a ping sound for every ping.
> This works, but presents me with a problem. In order to continuously
> ping using the "-t" option for ping, I am unable to perform a
> readlines() command because it hangs. I've tried other variations of
> read commands, but they all hang my system. I guess it keeps looking
> for EOF and never finds it because the thing is still running. Is
> there a type of read command that just takes what is currently in the
> buffer and stores it?
The normal way is to use the select module, at least for unixy
systems.
%cat t.py
import os, select
class Ping:
def __init__(self, hostname):
self.hostname = hostname
timeout = len(hostname) % 5 + 3 # for some variation
self.infile = os.popen("ping -i %d %s" % (timeout, hostname))
def fileno(self):
return self.infile.fileno()
def readline(self):
return self.infile.readline()
def report(hostnames):
pings = [Ping(name) for name in hostnames]
while 1:
print "Waiting for another ping ...."
r, w, e = select.select(pings, [], [], 1)
for p in r:
print "Ping", p.hostname, p.readline()[:-1]
if __name__ == "__main__":
import sys
if len(sys.argv) == 1:
raise SystemExit("missing list of machines to ping")
else:
report(sys.argv[1:])
%python t.py biopython.org dalkescientific.com python.org
Waiting for another ping ....
Ping dalkescientific.com PING dalkescientific.com (66.39.47.217): 56 data
bytes
Waiting for another ping ....
Ping biopython.org PING biopython.org (155.94.54.81): 56 data bytes
Waiting for another ping ....
Ping python.org PING python.org (194.109.137.226): 56 data bytes
Waiting for another ping ....
Waiting for another ping ....
Waiting for another ping ....
Ping python.org 64 bytes from 194.109.137.226: icmp_seq=0 ttl=238
time=96.553 ms
Waiting for another ping ....
Ping python.org 64 bytes from 194.109.137.226: icmp_seq=1 ttl=238
time=94.554 ms
Waiting for another ping ....
Waiting for another ping ....
Waiting for another ping ....
Ping biopython.org 64 bytes from 155.94.54.81: icmp_seq=0 ttl=55 time=17.084
ms
You could also spawn off a thread for each one, but the select
approach is pretty simple. (See Aahz's thread tutorial for an example
of how to use threads for a similar task.)
Andrew
dalke at dalkescientific.com
More information about the Python-list
mailing list