python
runtime_error
ai_generated
true
RuntimeError: There is no current event loop in thread 'MainThread'.
ID: python/asyncio-event-loop-is-running-pytest
80%Fix Rate
88%Confidence
0Evidence
2024-03-06First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 3.10 | active | — | — | — |
| 3.11 | active | — | — | — |
| 3.12 | active | — | — | — |
Root Cause
Since Python 3.10, asyncio.get_event_loop() no longer creates a loop implicitly when called from a thread with no running loop; code that relied on the old behavior raises this error, common in pytest and background threads.
generic中文
自 Python 3.10 起,在没有运行循环的线程中调用 asyncio.get_event_loop() 不再隐式创建循环;依赖旧行为的代码会抛出此错误,常见于 pytest 和后台线程。
Workarounds
-
90% success
loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) try: loop.run_until_complete(main()) finally: loop.close() -
92% success
# pytest.ini: asyncio_mode = auto import pytest @pytest.mark.asyncio async def test_foo(): assert await foo() == 1
Dead Ends
Common approaches that don't work:
-
70% fail
Blocks upgrades and the behavior is slated for removal; not a durable fix.
-
85% fail
Makes get_event_loop raise immediately; does not provide a usable loop.