如何用按键杀死while循环? [英] How to kill a while loop with a keystroke?

查看:135
本文介绍了如何用按键杀死while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取串行数据并使用while循环写入csv文件。我希望用户一旦感到自己已经收集到足够的数据,便可以终止while循环。

I am reading serial data and writing to a csv file using a while loop. I want the user to be able to kill the while loop once they feel they have collected enough data.

while True:
    #do a bunch of serial stuff

    #if the user presses the 'esc' or 'return' key:
        break

我已经使用opencv做过类似的事情,但是它似乎在此应用程序中不起作用(而且我真的不想仅出于以下目的导入opencv:反正此函数)...

I have done something like this using opencv, but it doesn't seem to be working in this application (and i really don't want to import opencv just for this function anyway)...

        # Listen for ESC or ENTER key
        c = cv.WaitKey(7) % 0x100
        if c == 27 or c == 10:
            break

所以。我该如何让用户摆脱循环?

So. How can I let the user break out of the loop?

此外,我不想使用键盘中断,因为脚本需要在一段时间后继续运行循环终止。

Also, I don't want to use keyboard interrupt, because the script needs to continue to run after the while loop is terminated.

推荐答案

最简单的方法是使用通常的 Ctrl-C (SIGINT)。

The easiest way is to just interrupt it with the usual Ctrl-C (SIGINT).

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

由于 Ctrl-C 导致 KeyboardInterrupt 引发,只需将其捕获到循环外并忽略它即可。

Since Ctrl-C causes KeyboardInterrupt to be raised, just catch it outside the loop and ignore it.

这篇关于如何用按键杀死while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆