Search code examples
pythonwhile-loopbreak

How to kill a while loop with a keystroke?


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.


Solution

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