我正在尝试在jupyter 实验室上复制the official Asynchronous Widgets-Example,但是await
再也没有继续。
docker run --rm -p 8888:8888 -e JUPYTER_ENABLE_LAB=yes jupyter/datascience-notebook start-notebook.sh --NotebookApp.token=''
firefox 0.0.0.0:8888
%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 实验室,而不是普通的jupyter笔记本
没有错误消息或任何东西。预期的输出不会发生
最小的asyncio示例在jupyter实验室中有效:
import asyncio
async def main():
print('hello')
await asyncio.sleep(1)
print('world')
await main()
当您省略-e JUPYTER_ENABLE_LAB=yes
时,您会得到一台没有jupyter实验室的常规jupyter笔记本,并且会发生预期的结果。
这不是ipywidgets widgets values not changing或Jupyter Interactive Widget not executing properly的副本,因为这些问题包括jupyter lab或asyncio
答案 0 :(得分:1)
实际上可以,但是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
答案 1 :(得分:-1)
我很幸运使用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
为我工作。 希望有帮助!