ipython 笔记本中 while 循环的优雅中断

graceful interrupt of while loop in ipython notebook

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

我在一个 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

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

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

所以使用这个:

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

按照建议 here 并单击此菜单条目。