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

Python使用asyncio发起多请求遇RuntimeError问题求助

问题原因与解决方法

错误原因

  1. 事件循环冲突:你用loop.run_until_complete()手动启动事件循环,但当前运行环境(比如Jupyter Notebook、IPython、部分异步框架)已经自动启动了一个事件循环,同一线程里不能同时存在两个运行中的事件循环,因此抛出RuntimeError。
  2. 代码逻辑问题:return await data是冗余操作——data = await resp.json()已经完成异步解析,直接返回data即可;另外原代码把asyncio.gather放在async with aiohttp.ClientSession()块外,会导致session提前关闭,任务执行时会报错。

解决方法

场景1:普通Python脚本环境(无预运行事件循环)

用Python 3.7+推荐的asyncio.run()方法,它会自动管理事件循环的创建、运行和关闭,同时修正session上下文的问题:

import asyncio
import aiohttp

async def get_item(session: aiohttp.ClientSession, path: str):
    url = f'my/path/here{path}'
    resp = await session.request('GET', url=url)
    data = await resp.json()
    # 在这里处理数据并保存为csv
    return data

async def get_all():
    async with aiohttp.ClientSession() as session:
        tasks = [
            get_item(session=session, path='1'),
            get_item(session=session, path='2')
        ]
        # 在session上下文内执行任务,避免session提前关闭
        results = await asyncio.gather(*tasks, return_exceptions=True)
    return results

if __name__ == "__main__":
    asyncio.run(get_all())

场景2:已有运行中事件循环的环境(如Jupyter/IPython)

直接在交互式环境中执行await get_all()即可,无需手动启动循环:

# 先定义好get_item和get_all函数
await get_all()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 14:18:15