Blessoul Blessoul - 6 months ago 54
Python Question

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):

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.


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

    while True:
except KeyboardInterrupt:
    print 'interrupted!'

Then you can exit the loop with CTRL-C.