#!/usr/bin/env python3 # -*- coding: utf-8 -*- from gevent import monkey monkey.patch_all() import gevent import urllib.request def run_task(url): print('Visit --> %s' % url) try: response = urllib.request.urlopen(url) data = response.read() print('%d bytes received from %s.' % (len(data), url)) except Exception as e: print(e) if __name__ == '__main__': urls = ['https://www.baidu.com','https://docs.python.org/3/library/urllib.html','https://www.cnblogs.com/wangmo/p/7784867.html'] greenlets = [gevent.spawn(run_task, url) for url in urls] gevent.joinall(greenlets)
运行结果如下:
Visit --> https://www.baidu.com Visit --> https://docs.python.org/3/library/urllib.html Visit --> https://www.cnblogs.com/wangmo/p/7784867.html 227 bytes received from https://www.baidu.com. 9850 bytes received from https://docs.python.org/3/library/urllib.html. 28483 bytes received from https://www.cnblogs.com/wangmo/p/7784867.html. Process finished with exit code 0