簡體   English   中英

RuntimeError:無法從正在運行的事件循環中調用 asyncio.run()

[英]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

這是一個與 IPython 相關的已知問題

您已經發現的一種方法是使用nest_asyncio

import nest_asyncio
nest_asyncio.apply()

另一種是安裝舊版本的tornado

pip3 install tornado==4.5.3

問題根源

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 的建議

  1. 通過創建新任務附加到現有的 Spyder 線程事件循環
import asyncio

async def main():
    print('Hello world!')

asyncio.create_task(main())
  1. 創建允許運行我們自己的事件循環的新線程(通過在外部終端中執行)。
    頂部菜單Run -> Run configuration per file... -> Execute in the external system terminal 在此處輸入圖片說明

現在代碼在新終端中運行並工作

import asyncio

async def main():
    print('Hello world!')
asyncio.run(main())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM