python runtime_error ai_generated true

RuntimeError: 线程 'MainThread' 中没有当前事件循环。

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

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

其他格式: JSON · Markdown 中文 · English
80%修复率
88%置信度
0证据数
2024-03-06首次发现

版本兼容性

版本状态引入弃用备注
3.10 active — — —
3.11 active — — —
3.12 active — — —

根因分析

自 Python 3.10 起,在没有运行循环的线程中调用 asyncio.get_event_loop() 不再隐式创建循环;依赖旧行为的代码会抛出此错误,常见于 pytest 和后台线程。

English

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

解决方案

  1. 90% 成功率
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    try:
        loop.run_until_complete(main())
    finally:
        loop.close()
  2. 92% 成功率
    # pytest.ini: asyncio_mode = auto
    import pytest
    @pytest.mark.asyncio
    async def test_foo():
        assert await foo() == 1

无效尝试

常见但无效的做法:

  1. 70% 失败

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

  2. 85% 失败

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