gevent 实现多协程的时候,出现了上面的错误
错误的代码如下:
import requests
from gevent import monkey
monkey.patch_all()
import gevent
def f(url):
print('GET: %s' % url)
data = requests.get(url).text
print('%d bytes received from %s.' % (len(data), url))
gevent.joinall([
gevent.spawn(f, 'https://www.python.org/'),
gevent.spawn(f, 'https://www.yahoo.com/'),
gevent.spawn(f, 'https://github.com/'),
])
比较纠结,因为在网上大家似乎都是这么写的呀?为什么我会报错了??
查了半天也没查到有关的信息, 后来我在github上看到一篇讲gevent - ‘module’ object has no attribute ‘epoll’的时候,虽然也没有看到些上面,但是看到评论区中有人说了这样的话
I agree that monkey patching has to be done before everything. I have a django app running with uwsgi+supervisord config. And gevent.monkey.patch_all() was the first line of wsgi.py (which is the entry point to the app). But still this exception was thrown. So either adding –gevent-early-monkey-patch in the uwsgi config or gevent.monkey.patch_all(select=False) in the wsgi.py fixed the error. I’m not sure that this is relevant to the requests or urllib3 libs but just for someone’s information.
看到最后那句话的时候,突然灵光一闪!这不是刚好解释了我的问题了么?
因为我的报错正是关于select
的呀!虽然我写的代码没有用到那个config,但是我也是在这里遇到了问题了呀!
AttributeError: module ‘select’ has no attribute ‘error’
所以正确的解法应该是:
import requests
from gevent import monkey
monkey.patch_all(select=False)
import gevent
def f(url):
print('GET: %s' % url)
data = requests.get(url).text
print('%d bytes received from %s.' % (len(data), url))
gevent.joinall([
gevent.spawn(f, 'https://www.python.org/'),
gevent.spawn(f, 'https://www.yahoo.com/'),
gevent.spawn(f, 'https://github.com/'),
])
然后,我们就可以很愉快的开始我们的表演了:请看下面的gif
嘿嘿嘿~ 这样我们在不同的协程中,只要遇到了IO或者网络上的问题,就直接切换了~
Hello gevent~
最后,老套路,宣传一波自己的公众号!(求关注哇!)
本人中大一肥宅,欢迎大家关注,请扫下面的二维码(〃’▽’〃)
如果觉得有帮助的话,可以扫码,赞赏鼓励一下!谢谢!