运行pytest时遇AttributeError:_UnixSelectorEventLoop无_signal_handlers属性
Mac M1 PyCharm启动pytest触发asyncio AttributeError问题
错误信息
Connected to pydev debugger (build 233.15026.15) Exception ignored in: <function BaseEventLoop.__del__ at 0x12809be50> Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.19/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 688, in __del__ self.close() File "/usr/local/Cellar/python@3.9/3.9.19/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/unix_events.py", line 60, in close for sig in list(self._signal_handlers): AttributeError: '_UnixSelectorEventLoop' object has no attribute '_signal_handlers' Exception ignored in: <function BaseEventLoop.__del__ at 0x12809be50> Traceback (most recent call last): File "/usr/local/Cellar/python@3.9/3.9.19/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 688, in __del__ self.close() File "/usr/local/Cellar/python@3.9/3.9.19/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/unix_events.py", line 60, in close for sig in list(self._signal_handlers): AttributeError: '_UnixSelectorEventLoop' object has no attribute '_signal_handlers' Launching pytest with arguments <args here>
解决方案
- 升级PyCharm:该错误源于PyCharm调试器(pydev)与M1架构下Python 3.9 asyncio的兼容性问题,更新至2024.x及以上版本的PyCharm可直接修复。
- 更换Python解释器:
- 打开
File > Settings > Project: [项目名] > Python Interpreter - 替换为系统自带Python或通过conda创建适配M1的虚拟环境,避免使用Homebrew安装的Python 3.9(部分版本存在asyncio底层bug)
- 打开
- 调整调试器配置:
- 进入
Run > Edit Configurations - 选中你的pytest配置,在
Configuration页勾选Emulate terminal in output console - 或添加环境变量
PYDEVD_DISABLE_ASYNCIO_SUPPORT=1到配置的Environment variables中
- 进入
- 手动初始化事件循环属性:在项目根目录的
conftest.py中添加以下代码,提前初始化缺失的属性:
import asyncio from asyncio import UnixSelectorEventLoop def pytest_configure(config): loop = UnixSelectorEventLoop() if not hasattr(loop, '_signal_handlers'): loop._signal_handlers = {} asyncio.set_event_loop(loop)
内容的提问来源于stack exchange,提问作者prabodhprakash
相关产品推荐
相关产品推荐

