Jupyter笔记本中的交互式计时器

时间:2017-03-29 08:10:19

标签: jupyter-notebook jupyter ipywidgets

我有一个记录数据的功能,需要一段时间才能完成。在记录数据的同时,我想要一个按钮,按下该按钮,显示自数据采集开始以来经过的时间。

这可以在Jupyter中做到吗?

我遇到问题,因为数据采集会阻止小部件激活,如果我尝试在后台运行小部件,则在数据采集之前它不会收到on_click事件已完成。另一方面,如果我将数据采集发送到后台,那么一旦后台作业完成,数据就会丢失。

后台工作

from IPython.lib.backgroundjobs import BackgroundJobManager
from IPython.core.magic import register_line_magic
from IPython import get_ipython

jobs = BackgroundJobManager()

@register_line_magic
def background_job(line):
    ip = get_ipython()
    jobs.new(line, ip.user_global_ns)

计时器按钮

import ipywidgets as widgets
import time

def button_timer():
    t0 = 0
    button = widgets.Button(description="Measure time")
    def action(b):
        time_elapsed = time.perf_counter() - t0
        display("Time elapsed: {}".format(time_elapsed))
    button.on_click(action)

    display(button)
    t0 = time.perf_counter()

数据采集

import numpy as np
import pandas as pd
import time

def acquire(a=None):
    time.sleep(10)
    print("Done")
    if a is None:
        return np.linspace(0, 10, 10)
    else:
        a = np.linspace(0, 10, 10)

## Implementation 1
# This fails because the `on_click` event for the button only runs after the data has been acquired.
button_timer()
data = pd.DataFrame()
data['x'] = np.linspace(0, 10, 10)
data['y'] = acquire()

## Implementation 2
# As before, the `on_click` event isn't activated until after the data has been acquired.
%background_job button_timer()
data = pd.DataFrame()
data['x'] = np.linspace(0, 10, 10)
data['y'] = acquire()

## Implementation 3
# This one fails as the data isn't actually updated
button_timer()
data = pd.DataFrame()
data['x'] = np.linspace(0, 10, 10)
# I can't use the equal sign as that isn't supported by the background job.
# %background_job data['y'] = acquire()
# If I pass in the data I want, the DataFrame isn't updated (even after I wait for the background job to finish)
%background_job acquire(data['y'])
display(data)

如果所有其他方法都失败了,我想一个选择就是拥有一个完全在浏览器中运行的仅限Javascript的计时器。

尽管如此,我还是想知道在Python中是否有这样做的方式(如果可能的话,让它在计算机上可以在笔记本的其余部分中访问)。 / p>

0 个答案:

没有答案