RuntimeError:无法从正在运行的事件循环中调用 asyncio.run() [英] RuntimeError: asyncio.run() cannot be called from a running event loop

查看:162
本文介绍了RuntimeError:无法从正在运行的事件循环中调用 asyncio.run()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试了解 websockets 客户端的 asyncio.我尝试的每一段代码都会出现以下错误:

I am trying to learn about asyncio for a websockets client. Every piece of code I try gets the following error:

运行时错误:无法从正在运行的事件循环中调用 asyncio.run()

RuntimeError: asyncio.run() cannot be called from a running event loop

我尝试了最简单的代码,它总是给出 RuntimeError.我尝试再次安装完整的 anaconda 发行版等,但找不到可能是什么问题.

I have tried the most simple code and it always gives that RuntimeError. I tried installing the full anaconda distribution again, etc, and can´t find what the problem might be.

我在 Python 3.7.3 中使用 Spyder 3.3.3

I am using Spyder 3.3.3 with Python 3.7.3

应该可以工作的代码示例:

An example of code that should work:

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

推荐答案

一个已知问题 与 IPython 相关.

It's a known problem related to IPython.

您已经发现的一种方法是使用 nest_asyncio:

import nest_asyncio
nest_asyncio.apply()

另一个是安装旧版本的龙卷风:

pip3 install tornado==4.5.3

这篇关于RuntimeError:无法从正在运行的事件循环中调用 asyncio.run()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆