簡體   English   中英

%time await main() throws SyntaxError: 'await' outside function in jupyter

[英]%time await main() throws SyntaxError: 'await' outside function in jupyter

我嘗試在 Jupyter-notebook 中使用%time來計算時間,一些 SyntaxError 讓我感到困惑。 這是一個可以演示問題的簡單代碼

import asyncio
async def main():
    print(1)
    
%time asyncio.run(main())

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

根據asyncio.run() 不能從正在運行的事件循環中調用,我像這樣更改代碼

import asyncio
async def main():
    print(1)
    
%time await main()

SyntaxError: 'await' outside function

當我刪除%time部分時,代碼工作正常。

jupyter 不支持%time和 asyncio 函數嗎?

不幸的是,ipython(因此是 juypter)不支持魔法與異步的互操作性。

https://ipython.readthedocs.io/en/stable/interactive/autoawait.html#effects-on-magics

一些魔法(%%timeit、%timeit、%%time、%%prun)尚未更新以適用於異步代碼,並且在嘗試使用頂級等待時會引發語法錯誤。 我們歡迎任何有助於解決這些問題的貢獻,以及我們尚未發現的額外案例。 我們希望 Core Python 能夠更好地支持頂級異步代碼。

暫無
暫無

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

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