Cool use for a generator?

André arisen at
Mon Jul 9 12:43:10 CEST 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.

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

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

André Risnes

More information about the Python-list mailing list