Python 3.11 的 gather 一个协程抛错 为什么其余任务还在跑

陆零云 32 0
批量抓取脚本用 Python 3.11 的 asyncio,200 个页面并发,任务列表直接丢给 gather,没加 return_exceptions。跑到第 37 个时某个页面返回 404,aiohttp 抛 ClientResponseError,整个 gather 立刻把异常抛出来,主函数退出。 第一反应是进程挂了,看日志才发现后面还有十几条 Task was destroyed but it is pending 的告警。gather 在第一个异...

asyncio.run 报 RuntimeError:线程里已有事件循环怎么改

陆零云 37 0
报错原文是 RuntimeError: asyncio.run() cannot be called from a running event loop,栈底那行落在 uvicorn 的 run_until_complete 上。Python 3.11 加 FastAPI,一个 async 端点里调了旧代码封装的同步函数,那个函数内部又用 asyncio.run 去拉起 httpx.AsyncClient。这段代码上线半年没动过,加了一条新路由才把它带出来...