[英]RuntimeError: asyncio.run() cannot be called from a running event loop
I am running the simplest of examples on asyncio:我在 asyncio 上运行最简单的示例:
import asyncio
async def main():
print("A")
await asyncio.sleep.sleep(1)
print("B")
asyncio.run(main())
and I get a runtime error: RuntimeError: asyncio.run() cannot be called from a running event loop我收到运行时错误:RuntimeError: asyncio.run() cannot be called from a running event loop
I am using Spyder (Python 3.9) on an M1 Mac (...if that matters).我在 M1 Mac 上使用 Spyder(Python 3.9)(...如果重要的话)。
the outcome expected is:预期的结果是:
A一种
B乙
Process finished with exit code 0进程结束,退出代码为 0
But for the ".sleep.sleep" this code is fine - "event loop already running" is certainly not an issue for a standalone script with this code.但是对于“.sleep.sleep”,这段代码很好——“事件循环已经在运行”对于使用这段代码的独立脚本来说肯定不是问题。
Maybe you are running it in as a notebook cell, with some asyncio state already set-up?也许您正在将它作为笔记本单元运行,并且已经设置了一些 asyncio state?
In a bash terminal, I pasted your code as is, and just replaced the incorrect function name:在 bash 终端中,我按原样粘贴了您的代码,只是替换了不正确的 function 名称:
[gwidion@fedora tmp01]$ cat >bla42.py
import asyncio
async def main():
print("A")
await asyncio.sleep.sleep(1)
print("B")
asyncio.run(main())
[gwidion@fedora tmp01]$ python bla42.py
A
Traceback (most recent call last):
[...]
File "/home/gwidion/tmp01/bla42.py", line 5, in main
await asyncio.sleep.sleep(1)
AttributeError: 'function' object has no attribute 'sleep'
[gwidion@fedora tmp01]$ python -c 'open("bla43.py", "w").write(open("bla42.py").read().replace(".sleep.sleep", ".sleep"))'
[gwidion@fedora tmp01]$ python bla43.py
A
B
[gwidion@fedora tmp01]$
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.