在最新的python3.6中使用协程,启用gevent时,可能会出现警告,代码如下:
import gevent
from gevent import monkey
monkey.patch_all()
# monkey.patch_socket()
# monkey.patch_ssl()
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://github.com/', 'https://www.python.org/', 'http://www.cnblogs.com/']
greenlets = [gevent.spawn(run_task, url) for url in urls]
gevent.joinall(greenlets)
运行结果如下所示:
MonkeyPatchWarning: Monkey-patching ssl after ssl has already been imported may lead to errors, including RecursionError on Python 3.6.
Please monkey-patch earlier. See https://github.com/gevent/gevent/issues/1016
monkey.patch_all()
Visit --> https://github.com/
Visit --> https://www.python.org/
Visit --> http://www.cnblogs.com/
46365 bytes received from http://www.cnblogs.com/
48801 bytes received from https://www.python.org/
59467 bytes received from https://github.com/
而访问 https://github.com/gevent/gevent/issues/1016后可知,方法是将
import gevent
import gevent.monkey
>>> gevent.monkey.patch_all()
置顶,但再次运行后发现依然出现相同的红色警告,这是因为python3.6自带的gevent版本过低所致,卸载后重新安装最新
gevent版本即可。
解决方案:
pip uninstall gevent
pip install gevent
再次运行成功,搞定。