[英]Combining loop.run_until_complete and asnycio.gather results in RuntimeError: This event loop is already running
[英]RuntimeError: asyncio.run() cannot be called from a running event loop
我在 asyncio 上運行最簡單的示例:
import asyncio
async def main():
print("A")
await asyncio.sleep.sleep(1)
print("B")
asyncio.run(main())
我收到運行時錯誤:RuntimeError: asyncio.run() cannot be called from a running event loop
我在 M1 Mac 上使用 Spyder(Python 3.9)(...如果重要的話)。
預期的結果是:
一種
乙
進程結束,退出代碼為 0
但是對於“.sleep.sleep”,這段代碼很好——“事件循環已經在運行”對於使用這段代碼的獨立腳本來說肯定不是問題。
也許您正在將它作為筆記本單元運行,並且已經設置了一些 asyncio state?
在 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.