anaconda spyder使用协程报错解决:RuntimeError: This event loop is already running

在Anaconda的Spyder环境中编写协程代码时遇到'RuntimeError: This event loop is already running'错误。该问题在GitHub上已有讨论,可能由于Spyder或aiohttp、asyncio与IDE的不兼容导致。尝试更新到最新版本未解决问题。解决方案包括:1) 不使用Spyder内核,改用Jupyter Notebook或终端运行程序;2) 安装`nest-asyncio`库,并在代码开头导入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

早上在anaconda的spyder中写协程代码时遇到了报错。
代码如下:

import asyncio

async def coroutine():
    print("hey")
    await asyncio.sleep(1)

asyncio.get_event_loop().run_until_complete(coroutine())

报错如下:

Python 3.7.4 (default, Aug  9 2019, 18:34:13) [MSC v.1915 64 bit (AMD64)]
Type "copyright", "credits" or "license" for more information.

IPython 7.8.0 -- An enhanced Interactive Python.
In [1]:runfile('C:/Users/peter/untitled0.py', wdir='C:/Users/peter')
Traceback (most recent call last):

  File "<ipython-input-1-cf6eb8713524>", line 1, in <module>
    runfile('C:/Users/peter/untitled0.py', wdir='C:/Users/peter')

  File "C:\Users\peter\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
    execfile(filename, namespace)

  File "C:\Users\peter\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/peter/untitled0.py", line 7, in <module>
    asyncio.get_event_loop().run_until_complete(coroutine())

  File "C:\Users\peter\Anaconda3\lib\asyncio\base_events.py", line 566, in run_until_complete
    self.run_forever()

  File "C:\Users\peter\Anaconda3\lib\asyncio\base_events.py", line 521, in run_forever
    raise RuntimeError('This event loop is already running')

RuntimeError: This event loop is already running

这个问题在GitHub上已经有人提过了:
“RuntimeError: This event loop is already running”; debugging aiohttp, asyncio and IDE “spyder3” in python 3.6.5 · Issue #7096 · spyder-ide/spyder
async support by minrk · Pull Request #323 · ipython/ipykernel
问题出现的原因是IPython/ipykernel不支持asyncio
根据说明,IPython最新版本可能修复了问题,先尝试更新到最新版本IPython 7.10.2
没解决问题。

解决方法1

不用spyder,用pychram或者终端直接跑程序,就没这个问题。

解决方法2

安装nest_asyncio

pip install nest_asyncio

在代码开头加上:

import nest_asyncio
nest_asyncio.apply()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值