调用gevent.select.poll出现AttributeError/ImportError如何解决
问题核心原因
- 平台兼容性限制:gevent的
poll类是对系统原生poll接口的封装,仅在POSIX兼容系统(Linux、macOS等)下存在,Windows系统原生没有poll接口,因此gevent也不会提供对应实现,此时导入就会抛出不存在的错误。 - 条件导出逻辑:gevent的
select模块只有检测到当前Python标准库select模块原生支持poll接口时,才会定义自己的poll实现。如果你的Python是裁剪过的发行版,原生select就没有poll属性,gevent的select模块也不会导出poll类。 - 补丁参数问题:默认的
monkey.patch_all()虽然会patchselect模块,但旧版本gevent可能不会主动暴露poll接口到模块顶层。
解决方案
- 首先验证环境是否原生支持
poll,运行以下代码检查:
import select print(hasattr(select, 'poll'))
如果返回False,说明你的运行环境本身不支持poll接口,需要更换POSIX系统下的标准Python发行版。
- 环境支持的前提下如果还是导入失败,先升级gevent到最新稳定版本:
pip install --upgrade gevent
- 如果你不需要
poll操作异步非阻塞,可以在打补丁时排除select模块,直接使用原生poll:
from gevent import monkey # 打补丁时排除select模块,保留原生select的所有接口 monkey.patch_all(select=False) import select p = select.poll() p.register(fd, select.POLLERR | select.POLLPRI) while True: if p.poll(): # 执行你的业务逻辑 pass
注意:该方案下p.poll()是阻塞调用,会卡住gevent的主事件循环,如果你需要异步执行,可以把这段逻辑放到gevent的线程池中运行:
from gevent import monkey monkey.patch_all(select=False) from gevent.threadpool import ThreadPoolExecutor import select def monitor_sys_path(fd): p = select.poll() p.register(fd, select.POLLERR | select.POLLPRI) while True: if p.poll(): # 执行你的业务逻辑 pass # 用线程池运行阻塞的poll逻辑,不影响主事件循环 executor = ThreadPoolExecutor(max_workers=1) executor.submit(monitor_sys_path, your_fd)
- 如果需要
poll操作兼容gevent的异步调度,可以直接从gevent的内部实现导入(仅适用于20.04.0及以上版本的gevent):
from gevent.select import poll p = poll() p.register(fd, select.POLLERR | select.POLLPRI)
内容的提问来源于stack exchange,提问作者user9763248
相关产品推荐
相关产品推荐

