Ending an infinite while loop

Blessoul picture Blessoul · Sep 25, 2013 · Viewed 80.8k times · Source

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.

Answer

Steve Howard picture Steve Howard · Sep 25, 2013

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.