python runtime_error ai_generated true

RuntimeError: There is no current event loop in thread 'MainThread'.

ID: python/asyncio-event-loop-is-running-pytest

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-06First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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

  1. 90% success
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(main())
    finally:
        loop.close()
  2. 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:

  1. 70% fail

    Blocks upgrades and the behavior is slated for removal; not a durable fix.

  2. 85% fail

    Makes get_event_loop raise immediately; does not provide a usable loop.