python - 有没有办法直接在Jupyter cell中调用await?

标签 python python-3.x async-await jupyter-notebook python-asyncio

我见过在某些环境中运行此类代码的示例(例如 https://github.com/ipython/ipykernel/pull/323)。

但对我来说,到目前为止,这只会引发 SyntaxError:

enter image description here

更新:

我知道在“纯”python 中它不会工作并且 await 应该只在 async def 中使用。

我也知道在 jupyter 中它是可能的(见上面的链接)所以引擎能够做到这一点。问题是如何摆脱此错误消息。

更新2 直接调用await是什么思路:

我正在使用异步库。在当前版本的 jupyter 中,很难获得协程的返回值:

enter image description here 我想到的最好的事情是通过全局变量:

enter image description here

这里的一个问题是单元格 25 中的 res 还没有准备好。我必须等到看到“完成”,然后使用另一个单元格中的值。

另一个问题是直接从单元格调用协程和从另一个协程调用协程之间的语义不对称,这在编辑器中编写脚本时非常无关紧要,但对于 repl 却非常重要。

现在考虑一下:

enter image description here

最佳答案

知道了!

enter image description here

这需要安装 IPython 的开发版本(https://github.com/ipython/ipython/pull/11155)。

这是:

pip 安装 git+ https://github.com/minrk/ipython.git@more-await-repl#egg=ipython

pip 安装 git+ https://github.com/minrk/ipykernel.git@run-async#egg=ipykernel

更新:

正如@ack 所指出的,现在这个功能出现在 pypi 上的最新版本 ipykernel 中。

关于python - 有没有办法直接在Jupyter cell中调用await?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50833802/

相关文章:

python - 为 Django/Python 3 配置 Azure

python - 将否定文本转换为python中的文本

c# - 在 C# 中,如何在使用 WebClient.DownloadStringTaskAsync 方法时设置超时?

javascript - 在 promise 内部,我想将值(该值本身来自另一个 promise )分配给将在该 promise 之外使用的变量

Python 统计模型 OLS : how to save learned model to file

python - 为什么在打印 net 时没有列出 torch.nn.Parameter?

python - Django 'str' 对象在 rest_framework 中没有属性 'values'

python - 如何在具有现有列的数据框中设置多级索引

python - 如何修复:unsatisfiableerror: the following specifications were found to be in conflict

javascript - 类型错误 : fs. createReadStream 不是函数