How to kill a while loop with a keystroke? How to kill a while loop with a keystroke? python python

How to kill a while loop with a keystroke?


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

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

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


There is a solution that requires no non-standard modules and is 100% transportable

import threaddef input_thread(a_list):    raw_input()    a_list.append(True)def do_stuff():    a_list = []    thread.start_new_thread(input_thread, (a_list,))    while not a_list:        stuff()


the following code works for me. It requires openCV (import cv2).

The code is composed of an infinite loop that is continuously looking for a key pressed. In this case, when the 'q' key is pressed, the program ends. Other keys can be pressed (in this example 'b' or 'k') to perform different actions such as change a variable value or execute a function.

import cv2while True:    k = cv2.waitKey(1) & 0xFF    # press 'q' to exit    if k == ord('q'):        break    elif k == ord('b'):        # change a variable / do something ...    elif k == ord('k'):        # change a variable / do something ...