我正在尝试了解Websockets客户端的asyncio。我尝试的每段代码都会出现以下错误:
RuntimeError:无法从正在运行的事件循环中调用asyncio.run()
我尝试了最简单的代码,它始终会给出RuntimeError。我尝试再次安装完整的anaconda发行版,等等,但找不到问题所在。
我正在将Spyder 3.3.3与Python 3.7.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
答案 0 :(得分:4)
a known problem与IPython有关。
One way如您所知将使用nest_asyncio
:
import nest_asyncio
nest_asyncio.apply()
The other one是要安装tornado
的旧版本:
pip3 install tornado==4.5.3
答案 1 :(得分:3)
Spyder 运行自己的事件循环
print(asyncio.get_running_loop().is_running())
Returns: True
但每个线程只允许一个
<块引用>cannot be called when another asyncio event loop is running in the same thread
这就是为什么,当我们尝试使用
创建一个新的事件循环时
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())