有没有一种方法可以在Jupyter单元中直接呼叫await? [英] Is there a way to call await directly in Jupyter cell?

查看:97
本文介绍了有没有一种方法可以在Jupyter单元中直接呼叫await?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到了在某些环境中运行此类代码的示例(例如 https://github .com/ipython/ipykernel/pull/323 ).

I've seen examples of such code working in certain environments (eg https://github.com/ipython/ipykernel/pull/323).

但是对我而言,到目前为止只提高了SyntaxError:

But for me this only raises SyntaxError so far:

更新:

我知道在纯" python中它将无法工作,并且await应该仅在async def中使用.

I know that in "pure" python it won't work and await is supposed to be used in async def's only.

我还知道在jupyter中有可能 (请参见上面的链接),因此引擎能够做到这一点.问题是如何摆脱此错误消息.

I also know that in jupyter it is possible (see link above) so the engine is capable of doing this. The question is how to get rid of this error message.

更新2 直接调用await的想法是什么:

Update2 What's the idea of calling await directly:

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

I'm working with an async library. In current version of jupyter it's hard to get the return value of a coroutine:

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

The best thing I've come up to is through global variables:

这里的问题之一是res在单元格25中尚未准备好.我必须等到看到完成",然后在另一个单元格中使用该值.

One of the problems here is that res is not ready in the cell 25 yet. I have to wait until I see "done", then use the value in the another cell.

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

Another problem is semantic asymmetry between calling a coroutine from the cell directly and from another coroutine, which is pretty irrelevant when writing scripts in an editor, but quite crucial for repl.

现在考虑一下:

推荐答案

知道了!

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

哪个是:

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

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

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

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

更新:

正如@ack所指出的那样,如今,此功能存在于pypi的最新版本ipykernel中.

As noted by @ack, nowadays this functionality is present in the latest version ipykernel on pypi.

这篇关于有没有一种方法可以在Jupyter单元中直接呼叫await?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆