我如何在Jupyter Lab上使用异步小部件?

8

如何在jupyter lab上使用异步小部件?

我正在尝试在jupyter lab上复制官方异步小部件示例,但是await无法继续执行。

设置/复制

  1. docker run --rm -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes jupyter/datascience-notebook start-notebook.sh --NotebookApp.token=''
  2. firefox 0.0.0.0:8888
  3. 创建一个新的python3笔记本
  4. 创建一个单元格并输入以下代码
  5. 运行单元格
  6. 移动滑块

单元格代码

%gui asyncio

import asyncio
def wait_for_change(widget, value):
    future = asyncio.Future()
    def getvalue(change):
        # make the new value available
        future.set_result(change.new)
        widget.unobserve(getvalue, value)
    widget.observe(getvalue, value)
    return future

from ipywidgets import IntSlider
slider = IntSlider()

async def f():
    for i in range(10):
        print('did work %s'%i)
        #x = await asyncio.sleep(1)
        x = await wait_for_change(slider, 'value')
        print('async function continued with value %s'%x)
asyncio.ensure_future(f())
#task = asyncio.create_task(f())
slider

预期结果

该单元格输出:

did work 0
async function continued with value 1
did work 1
async function continued with value 2
[...]

实际输出

第一个did work 0之后没有任何内容。

注释

  • 我特别是指 jupyter lab,而不是普通的 jupyter 笔记本。

  • 没有任何错误消息或其他提示,期望的输出只是没有发生。

  • 最小的 asyncio 示例在 jupyter lab 中可以正常工作:

import asyncio
async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')
await main()
2个回答

4

实际上它是有效的,但Jupyter丢失了打印输出。 尝试这段代码:

from IPython.display import display
import ipywidgets as widgets

out = widgets.Output()

import asyncio
def wait_for_change(widget, value):
    future = asyncio.Future()
    def getvalue(change):
        # make the new value available
        future.set_result(change.new)
        widget.unobserve(getvalue, value)
    widget.observe(getvalue, value)
    return future



from ipywidgets import IntSlider
slider = IntSlider()

# Now the key: the container is displayed (while empty) in the main thread
async def f():
    for i in range(10):
        out.append_stdout('did work %s'%i)
        x = await wait_for_change(slider, 'value')
        out.append_stdout('async function continued with value %s'%x)
asyncio.ensure_future(f())

display(slider)
display(out)

你可以在这里找到更多详细信息:https://github.com/jupyter-widgets/ipywidgets/issues/2567#issuecomment-535971252。该问题涉及it技术,请注意。

-1

我认为您的示例的基本机制与异步小部件的第3个示例沿着相同的方向,其实在jupyter lab上可以正常工作:https://ipywidgets.readthedocs.io/en/latest/examples/Widget%20Asynchronous.html#Updating-a-widget-in-the-background - wotanii

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接