Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 743
Brian HK Avatar asked Sep 25 '13 01:09

Brian HK


People also ask

How do you end the while loop?

Breaking Out of While Loops. To break out of a while loop, you can use the endloop, continue, resume, or return statement.

How do you make an infinite while loop?

while loop represents the infinite condition as we provide the '1' value inside the loop condition. As we already know that non-zero integer represents the true condition, so this loop will run infinite times. We can also use the goto statement to define the infinite loop.

What will happen if an infinite while loop runs?

An infinite loop, as the name suggests, is a loop that will keep running forever. If you accidentally make an infinite loop, it could crash your browser or computer. It is important to be aware of infinite loops so you can avoid them.

Can an infinite loop be broken?

An infinite loop will run indefinitely, until it is explicitly broken out of using either a break , exit or raise statement.


2 Answers

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.

like image 109
Steve Howard Avatar answered Oct 04 '22 11:10

Steve Howard


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.

like image 36
Tristan Avatar answered Oct 04 '22 11:10

Tristan