Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 400
Chris Avatar asked Nov 01 '12 16:11

Chris


People also ask

How do you break a while loop with a key press?

To end a while loop prematurely in Python, press CTRL-C while your program is stuck in the loop. This will raise a KeyboardInterrupt error that terminates the whole program. To avoid termination, enclose the while loop in a try/except block and catch the KeyboardInterrupt .

How do I stop a while true loop?

You can stop an infinite loop with CTRL + C . You can generate an infinite loop intentionally with while True . The break statement can be used to stop a while loop immediately.

How do you end a continuous loop?

You can also hit CTRL-Z (this puts the process in the Stopped state), and then type bg to get it running in the background again... Show activity on this post. You can press Ctrl + C .


1 Answers

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.

like image 119
Keith Avatar answered Sep 18 '22 09:09

Keith