Ending an infinite while loop

I currently have code that basically runs an infinite while loop to collect data from users. Constantly updating dictionaries/lists based on the contents of a text file. For reference:

while (True):
    IDs2=UpdatePoints(value,IDs2)
    time.sleep(10)

Basically, my problem is that I do not know when I want this to end, but after this while loop runs I want to use the information collected, not lose it by crashing my program. Is there a simple, elegant way to simply exit out of the while loop whenever I want? Something like pressing a certain key on my keyboard would be awesome.


Solution 1:

You can try wrapping that code in a try/except block, because keyboard interrupts are just exceptions:

try:
    while True:
        IDs2=UpdatePoints(value,IDs2)
        time.sleep(10)
except KeyboardInterrupt:
    print('interrupted!')

Then you can exit the loop with CTRL-C.

Solution 2:

You could use exceptions. But you only should use exceptions for stuff that isn't supposed to happen. So not for this.

That is why I recommand signals:

import sys, signal
def signal_handler(signal, frame):
    print("\nprogram exiting gracefully")
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

you should put this on the beginning of your program and when you press ctrl+c wherever in your program it will shut down gracefully

Code explanation:

You import sys and signals. Then you make a function that executes on exit. sys.exit(0) stops the programming with exit code 0 (the code that says, everything went good).

When the program get the SIGINT either by ctrl-c or by a kill command in the terminal you program will shutdown gracefully.

Solution 3:

I think the easiest solution would be to catch the KeyboardInterrupt when the interrupt key is pressed, and use that to determine when to stop the loop.

except KeyboardInterrupt:
    break

The disadvantage of looking for this exception is that it may prevent the user from terminating the program while the loop is still running.

Solution 4:

I use python to track stock prices and submit automated buy/sell commands on my portfolio. Long story short, I wanted my tracking program to ping the data server for info, and place trades off of the information gathered, but I also wanted to save the stock data for future reference, on top of being able to start/stop the program whenever I wanted.

What ended up working for me was the following:

trigger = True
while trigger == True:
 try:
  (tracking program and purchasing program conditions here)
 except:
  trigger = False

print('shutdown initialized')
df = pd.DataFrame...
save all the datas
print('shutdown complete')

etc.

From here, while the program is in the forever loop spamming away requests for data from my broker's API, using the CTRL-C keyboard interrupt function toggles the exception to the try loop, which nullifies the while loop, allowing the script to finalize the data saving protocol without bringing the entire script to an abrupt halt.

Hope this helps!

Resultant