本文介绍了IPython Notebook中的while循环的优美中断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ipython Notebook中运行一些数据分析.一台单独的计算机收集一些数据并将其保存到服务器文件夹中,我的笔记本电脑会定期扫描该服务器以查找新文件,然后进行分析.

I'm running some data analysis in ipython notebook. A separate machine collects some data and saves them to a server folder, and my notebook scans this server periodically for new files, and analyzes them.

我在while循环中执行此操作,该循环每秒检查一次新文件.目前,我已将其设置为在分析一定数量的新文件时终止.但是,我想在按下按键时终止.

I do this in a while loop that checks every second for new files. Currently I have set it up to terminate when some number of new files are analyzed. However, I want to instead terminate upon a keypress.

我尝试尝试捕获键盘中断,如下所示:

I have tried try-catching a keyboard interrupt, as suggested here: How to kill a while loop with a keystroke?

,但它似乎不适用于ipython Notebook(我正在使用Windows).

but it doesn't seem to work with ipython notebook (I am using Windows).

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

Using openCV's keywait does work for me, but I was wondering if there are alternative methods without having to import opencv.

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

I have also tried implementing a button widget that interrupts the loop, as such:

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

但是我看到循环基本上忽略了按钮的按下.

But I see that the loop basically ignores the button presses.

推荐答案

您可以通过菜单内核->中断"在笔记本中触发KeyboardInterrupt.

You can trigger a KeyboardInterrupt in a Notebook via the menu "Kernel --> Interrupt".

所以使用这个:

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

根据建议的此处,然后单击此菜单项.

as suggested here and click this menu entry.

这篇关于IPython Notebook中的while循环的优美中断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 03:18