早上在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 "" , 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
。
没解决问题。
不用spyder
,用pychram
或者终端直接跑程序,就没这个问题。
安装nest_asyncio
:
pip install nest_asyncio
在代码开头加上:
import nest_asyncio
nest_asyncio.apply()