How to kill a while loop with a keystroke?

2019-01-01 10:56发布

问题:

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

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.

回答1:

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.



回答2:

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

import thread

def 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()


回答3:

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 cv2

while 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 ...


回答4:

pyHook might help. http://sourceforge.net/apps/mediawiki/pyhook/index.php?title=PyHook_Tutorial#tocpyHook%5FTutorial4

See keyboard hooks; this is more generalized-- if you want specific keyboard interactions and not just using KeyboardInterrupt.

Also, in general (depending on your use) I think having the Ctrl-C option still available to kill your script makes sense.

See also previous question: Detect in python which keys are pressed



回答5:

There is always sys.exit().

The system library in Python\'s core library has an exit function which is super handy when prototyping. The code would be along the lines of:

import sys

while True:
    selection = raw_input(\"U: Create User\\nQ: Quit\")
    if selection is \"Q\" or selection is \"q\":
        print(\"Quitting\")
        sys.exit()
    if selection is \"U\" or selection is \"u\":
        print(\"User\")
        #do_something()