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