如何用击键杀死一个while循环?

新手上路,请多包涵

我正在读取串行数据并使用 while 循环写入 csv 文件。我希望用户在感觉收集到足够的数据后能够终止 while 循环。

 while True:
    #do a bunch of serial stuff

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

我已经使用 opencv 做了类似的事情,但它似乎并没有在这个应用程序中工作(而且我真的不想仅仅为了这个功能导入 opencv)……

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

所以。如何让用户跳出循环?

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

原文由 Chris 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 326
2 个回答

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

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

由于 Ctrl-C 导致 KeyboardInterrupt 被引发,只需在循环外捕获它并忽略它。

原文由 Keith 发布,翻译遵循 CC BY-SA 3.0 许可协议

有一个解决方案不需要非标准模块并且 100% 可移植:

 import _thread

def input_thread(a_list):
    raw_input()             # use input() in Python3
    a_list.append(True)

def do_stuff():
    a_list = []
    _thread.start_new_thread(input_thread, (a_list,))
    while not a_list:
        stuff()

原文由 user297171 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题