![](/img/trans.png)
[英]"asyncio.run() cannot be called from a running event loop" when using Jupyter Notebook
[英]RuntimeError: asyncio.run() cannot be called from a running event loop
我正在尝试了解 websockets 客户端的 asyncio。 我尝试的每一段代码都会出现以下错误:
RuntimeError:无法从正在运行的事件循环中调用 asyncio.run()
我尝试了最简单的代码,它总是给出 RuntimeError。 我尝试再次安装完整的 anaconda 发行版等,但找不到可能是什么问题。
我在 Python 3.7.3 中使用 Spyder 3.3.3
应该工作的代码示例:
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
asyncio.run(main())
错误信息:
File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 786, in runfile
execfile(filename, namespace)
File "C:\Users\jmart\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/jmart/Documents/asynk2.py", line 8, in <module>
asyncio.run(main())
File "C:\Users\jmart\Anaconda3\lib\asyncio\runners.py", line 34, in run
"asyncio.run() cannot be called from a running event loop")
RuntimeError: asyncio.run() cannot be called from a running event loop
Spyder 运行自己的事件循环
print(asyncio.get_running_loop().is_running())
Returns: True
但每个线程只允许一个
这就是为什么,当我们尝试创建一个新的事件循环时
asyncio.run(main())
它给了我们一个错误:
RuntimeError: asyncio.run() cannot be called from a running event loop
除了我已经提出的 nest_asyncio 和 Tornado 的建议
import asyncio
async def main():
print('Hello world!')
asyncio.create_task(main())
现在代码在新终端中运行并工作
import asyncio
async def main():
print('Hello world!')
asyncio.run(main())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.