【问题标题】:%time await main() throws SyntaxError: 'await' outside function in jupyter%time await main() throws SyntaxError: 'await' outside function in jupyter
【发布时间】:2020-12-10 09:16:34
【问题描述】:

我尝试在 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() cannot be called from a running event loop,我这样改代码

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

它会抛出SyntaxError: 'await' outside function

当我删除 %time 部分时,代码可以正常工作。

jupyter 不支持 %time 和 asyncio 函数吗?

【问题讨论】:

标签: python jupyter-notebook


【解决方案1】:

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

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

一些魔法 (%%timeit, %timeit, %%time, %%prun) 还没有 更新为使用异步代码并会引发语法错误 尝试使用顶级等待时。我们欢迎任何贡献 帮助解决这些问题,以及我们尚未发现的额外案件。我们希望 Core Python 中更好地支持顶级异步代码。

【讨论】:

    猜你喜欢
    • 2016-10-15
    • 2019-05-31
    • 2020-03-29
    • 1970-01-01
    • 2023-02-25
    • 1970-01-01
    • 2019-11-23
    相关资源
    最近更新 更多