![](/img/trans.png)
[英]"asyncio.run() cannot be called from a running event loop" when using Jupyter Notebook
[英]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
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 的建議
import asyncio
async def main():
print('Hello world!')
asyncio.create_task(main())
現在代碼在新終端中運行並工作
import asyncio
async def main():
print('Hello world!')
asyncio.run(main())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.