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

编写异步函数遇报错:asyncio.run()不能从运行中的事件循环调用

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

错误原因

asyncio.run()会创建新事件循环、执行异步任务并在结束后关闭循环。但如果当前线程已经存在正在运行的事件循环(比如Jupyter Notebook/IPython环境、或代码本身处于异步上下文),调用该方法就会触发该错误。

解决方案

情况1:在已有事件循环的环境中(如Jupyter)

直接获取当前运行的事件循环,用run_until_complete执行任务:

import asyncio
from urllib.parse import urlparse
import whois

url1=['www.google.com', 'www.youtube.com', 'www.facebook.com']

async def dnsRec(url):
    async with whois.whois(urlparse(url).netloc) as response:
        domain_detail = response.json()
        return domain_detail
    
async def main():
    tasks = [dnsRec(i) for i in url1]
    results = await asyncio.gather(*tasks)
    print(results)
    
def func():
    loop = asyncio.get_running_loop()
    loop.run_until_complete(main())

func()

情况2:代码处于异步上下文当中

如果func本身在异步函数内被调用,直接await main()即可,无需使用asyncio.run():

async def another_async_func():
    # 其他异步操作
    await main()

情况3:纯同步环境排查

如果是在普通Python脚本(非Jupyter、非异步上下文)中运行原代码仍报错,检查是否有其他代码提前启动了事件循环,确保asyncio.run()是首次触发事件循环的调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 21:24:27