簡體   English   中英

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

[英]How can I use Asynchronous Widgets on jupyter lab?

如何在 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. 移動 slider

單元格代碼

%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
[...]

實際 output

第一個did work 0

筆記

  • 我專門談論的是 jupyter實驗室,而不是常規的 jupyter 筆記本

  • 沒有錯誤消息或任何東西。 預期的 output 只是沒有發生

  • 最小的 asyncio-example 確實在 jupyter 實驗室中工作:

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

實際上它有效,但 jupyter 丟失打印 output。 試試這個代碼:

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

我很幸運使用 jupyter-ui-poll 將小部件活動與 Jupyter Python 內核同步:

https://github.com/Kirill888/jupyter-ui-poll

特別是我在這里使用它:

https://github.com/AaronWatters/jp_doodle/blob/master/jp_doodle/auto_capture.py

為我工作。 希望有幫助!

暫無
暫無

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

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