Search code examples
pythonwhile-loopinfinite-loop

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

  • 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.