【问题标题】:graceful interrupt of while loop in ipython notebookipython笔记本中while循环的优雅中断
【发布时间】:2016-09-13 20:05:00
【问题描述】:

我正在 ipython notebook 中运行一些数据分析。一台单独的机器收集一些数据并将它们保存到服务器文件夹中,我的笔记本会定期扫描该服务器以查找新文件并分析它们。

我在一个 while 循环中执行此操作,该循环每秒检查新文件。目前,我已将其设置为在分析一些新文件时终止。但是,我想在按键时终止。

我已尝试捕获键盘中断,如下所示:How to kill a while loop with a keystroke?

但它似乎不适用于 ipython 笔记本(我使用的是 Windows)。

使用 openCV 的 keywait 确实对我有用,但我想知道是否有其他方法无需导入 opencv。

我也尝试过实现一个中断循环的按钮小部件,例如:

from ipywidgets import widgets 
import time
%pylab inline

button = widgets.Button(description='Press to stop')
display(button)

class Mode():
    def __init__(self):
        self.value='running'

mode=Mode()

def on_button_clicked(b):
    mode.value='stopped'

button.on_click(on_button_clicked)

while True:
    time.sleep(1)
    if mode.value=='stopped':
        break

但我看到循环基本上忽略了按钮按下。

【问题讨论】:

  • 作为参考,这不起作用的原因是内核在完成运行单元之后才处理按钮单击。

标签: ipython interrupt jupyter-notebook ipywidgets


【解决方案1】:

您可以通过菜单“Kernel --> Interrupt”在笔记本中触发KeyboardInterrupt

所以用这个:

try:
    while True:
        do_something()
except KeyboardInterrupt:
    pass

按照here 的建议并单击此菜单项。

【讨论】:

  • KeyboardInterrupt 是停止按钮的工作原理。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-03
  • 1970-01-01
  • 2016-06-02
  • 2014-03-14
  • 2013-02-09
相关资源
最近更新 更多