如何通过击键杀死while循环? [英] How to kill a while loop with a keystroke?

查看:23
本文介绍了如何通过击键杀死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?

另外,我不想使用键盘中断,因为脚本需要在while循环终止后继续运行.

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天全站免登陆