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.
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 .
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With