Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python how can I manually end an infinite while loop that's collecting data, without ending the code and not using KeyboardInterrupt?

In my code I have a "while True:" loop that needs to run for a varying amount of time while collecting live data (3-5 hours). Since the time is not predetermined I need to manually end the while loop without terminating the script, so that it may continue to the next body of code in the script.

I do not want to use "input()" at the end of the loop, because then I have to manually tell it to continue looping every time it finishes the loop, I am collecting live data down to the half second, so this is not practical.

Also I do not want to use keyboard interrupt, have had issues with it. Are there any other solutions? All I have seen is try/except with "keyboardinterrupt"

def datacollect()
def datacypher()

while True:
    #Insert code that collects data here
    datacollect()

#end the while loop and continue on
#this is where i need help

datacypher()
print('Yay it worked, thanks for the help')

I expect to end the loop manually and then continue onto the code that acts upon the collected data.

If you need more details or have problem with my wording, let me know. I have only asked one question before. I am learning.

like image 211
rum404 Avatar asked Mar 04 '23 20:03

rum404


1 Answers

How about adding a key listener in a second thread? After you press Enter, you'll manually move the script to the next stage by means of a shared bool. The second thread shouldn't slow down the process since it blocks on input().

from threading import Thread
from time import sleep

done = False

def listen_for_enter_key_press():
    global done
    input()
    done = True

listener = Thread(target=listen_for_enter_key_press)
listener.start()

while not done:
    print('working..')
    sleep(1)

listener.join()

print('Yay it worked, thanks for the help')
like image 53
ggorlen Avatar answered Mar 10 '23 07:03

ggorlen