import asyncio

async def request(url): print('开始解析url', url) await asyncio.sleep(1) # 模拟耗时操作 print('解析url完成', url)

async def main(): c = request('www.baidu.com') task = asyncio.create_task(c) print(task) await task print(task)

loop = asyncio.get_event_loop() loop.run_until_complete(main())

这个错误是因为在事件循环中已经有一个协程在运行,而我们又尝试创建一个新的协程去运行,这会导致冲突。解决方法是要么使用同一个协程,要么在新的事件循环中运行新的协程。

解决方案:

  1. 使用同一个协程:将所有需要执行的任务放到同一个协程中,例如 main() 协程,通过 await 语句依次执行每个任务。
  2. 新的事件循环:在新的事件循环中运行新的协程,例如 loop.run_until_complete(main())

上面的示例代码使用的是第一种方案,将 request() 协程放到 main() 协程中执行,避免了冲突。

其他可能导致该错误的原因:

  • 循环中没有正确退出,导致事件循环一直在运行。
  • 代码中存在死循环,导致事件循环无法退出。
  • 代码中使用了阻塞操作,例如 time.sleep(),导致事件循环无法正常工作。

建议:

  • 尽量使用非阻塞操作,避免使用 time.sleep() 等阻塞操作。
  • 代码中要确保事件循环能够正常退出。
  • 对于需要执行多个任务的情况,建议使用 asyncio.gather()asyncio.wait() 等方法管理多个任务。
Python3.9 asyncio RuntimeError: 'This event loop is already running' 解决方法

原文地址: https://www.cveoy.top/t/topic/ojfA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录