You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

解决asyncio.run()无法在运行中事件循环调用的RuntimeError问题

解决RuntimeError: asyncio.run() cannot be called from a running event loop

这个错误的核心原因是你当前运行代码的环境已经存在一个活跃的事件循环(比如Jupyter Notebook、IPython交互式环境,或者其他异步框架),而asyncio.run()的设计是作为异步程序的独立入口点——它会自动创建、运行并销毁一个新的事件循环,因此和已有的循环冲突。

以下是几种可行的解决方法:

方法1:直接await主协程(适用于交互式环境)

在Jupyter/IPython这类支持直接执行await语句的环境中,直接替换掉asyncio.run(main()):

from pyracing.client import Client
import asyncio

username = 'My Email Address'
password = 'My Password'

ir = Client(username, password)

async def main():
    seasons_list = await ir.current_seasons()
    for season in seasons_list:
        if season.season_id == 2846:
            print(f'Schedule for {season.series_name_short}' 
                    f' ({season.season_year} S{season.season_quarter})')
            for t in season.tracks:
                print(f'\tWeek {t.race_week} will take place at {t.name} ({t.config})')

# 直接await主协程,复用当前环境的事件循环
await main()

方法2:复用当前运行的事件循环(通用兼容方案)

如果不确定运行环境,或者需要在已有循环的代码中执行,可以获取当前活跃的事件循环并提交任务:

from pyracing.client import Client
import asyncio

username = 'My Email Address'
password = 'My Password'

ir = Client(username, password)

async def main():
    seasons_list = await ir.current_seasons()
    for season in seasons_list:
        if season.season_id == 2846:
            print(f'Schedule for {season.series_name_short}' 
                    f' ({season.season_year} S{season.season_quarter})')
            for t in season.tracks:
                print(f'\tWeek {t.race_week} will take place at {t.name} ({t.config})')

# 获取当前运行的事件循环,提交任务
loop = asyncio.get_running_loop()
# 如果需要等待任务完成,用await;不需要的话直接create_task即可
await loop.create_task(main())

方法3:在独立脚本中运行(原生场景)

如果你的代码是在普通.py脚本中执行,确保没有其他异步代码提前启动事件循环,asyncio.run(main())本身是完全正常的。这种情况下错误不会出现,除非脚本里有其他地方已经创建并运行了事件循环。

内容的提问来源于stack exchange,提问作者Raul Gonzales

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 12:42:47