Created
April 10, 2013 08:50
-
-
Save tomsteele/5352988 to your computer and use it in GitHub Desktop.
Gevent example with gethostbyname
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 | |
import sys | |
import gevent | |
from gevent import socket | |
# lazy global variable for storing results | |
results = [] | |
# greenlet worker | |
def worker(name): | |
try: | |
# this is an async version of gethostbyname | |
res = socket.gethostbyname(name) | |
results.append({"name": name, "ip": res}) | |
except socket.gaierror: | |
pass | |
def main(): | |
domain = sys.argv[1] | |
name_file = sys.argv[2] | |
names = [] | |
with open(name_file) as f: | |
names = f.readlines() | |
names = ['{0}.{1}'.format(n.strip(), domain) for n in names] | |
# normally would use a list comprehension but i wanted the example | |
# to be clearer | |
# for each name in names we spawn a greenlet | |
jobs = [] | |
for name in names: | |
jobs.append(gevent.spawn(worker, name)) | |
# wait for all the greenlets to complete | |
gevent.joinall(jobs) | |
for result in results: | |
print 'Found {0} => {1}'.format(result['name'], result['ip']) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment