1

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')
Samu
  • 11
  • 4
  • Does this answer your question? [Pausing a thread using threading class](https://stackoverflow.com/questions/3262346/pausing-a-thread-using-threading-class) – TheMisir Apr 03 '21 at 21:11

0 Answers0