I am writing a function which records data until the user has finished. The time it takes for someone to record the data varies, and for this reason I cannot use a timed loop. Instead I use a while loop which is interrupted with a key press. The code below works but there is a limitation that bothers me: its not possible use a key combination other than CTRL+C. I have also tried threads with varied success. I would like to know if there is a better way to interrupt a while loop in a function or whether it is simply bad practice to have while loops in functions?
import time
count = 0
###FUNCTIONS###
def function_with_while(count):
try:
while True:
#This is where I get a datapoint from the serial buffer
count = count + 1
print('count:' + str(count) + ' press CTRL+C to exit function')
time.sleep(1)
except KeyboardInterrupt:
print('Counting interrupted')
pass
return count
###MAIN###
count = function_with_while(count)
print('Loops completed before interruption:' + str(count))
print('END OF MAIN')