Last active
October 5, 2016 05:17
-
-
Save LaoLiulaoliu/fbb7203b9d4b5e451c6c to your computer and use it in GitHub Desktop.
gevent example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
"""Resolve hostnames concurrently, exit after 60 seconds. | |
Under the hood, this might use an asynchronous resolver based on | |
c-ares (the default) or thread-pool-based resolver. | |
You can choose between resolvers using GEVENT_RESOLVER environment | |
variable. To enable threading resolver: | |
GEVENT_RESOLVER=thread python dns_mass_resolve.py | |
""" | |
import sys | |
import gevent | |
from gevent import socket | |
from gevent.pool import Pool | |
N = 1000 | |
# limit ourselves to max 100 simultaneous outstanding requests | |
pool = Pool(100) | |
finished = 0 | |
def job(url): | |
global finished | |
try: | |
try: | |
ip = socket.gethostbyname(url) | |
print('%s = %s' % (url, ip)) | |
except socket.gaierror: | |
ex = sys.exc_info()[1] | |
print('%s failed with %s' % (url, ex)) | |
finally: | |
finished += 1 | |
with gevent.Timeout(60, False): | |
for x in xrange(10, 10 + N): | |
print(pool.full()) | |
pool.spawn(job, '%s.com' % x) | |
pool.join() | |
print('finished within 60 seconds: %s/%s' % (finished, N)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment