Cool use for a generator?

André arisen at start.no
Mon Jul 9 06:43:10 EDT 2001


Assuming i got the generator concept correctly from PEP 255,
this little (untested) snippet shows how to process
asynchronous events in an "iterative fashion". Assuming
also that ping is an interface to the libping library
(which would be nice to have anyway. See e.g.
http://www.joedog.org/libping/docs/man/pinghost3.html)


import ping, time

def now():
    return time.time() * 1000   # We want milliseconds

def pinggen(host):
    while 1:
        then = now()
        if ping.pinghost(host) == 1:
            yield now() - then
        else:
            return

if __name__ == "__main__":
    hostname = "localhost"
    for pingtime in pinggen(hostname):
        print "Reply from %s: time=%.1f" % (hostname, pingtime)


--
Regards
André Risnes



More information about the Python-list mailing list