The case in general looks like this:
while 1:and the problem is how to get out of the loop gracefully without killing the program.
I'm aware of the following variants to deal with the situation:
- Ctrl-C/Crtl-D keyboard program termination. It works but kills whole program. It is possible to avoid that by exception processing of the error:
# on ctrl-d or ctrl-c
except (EOFError, KeyboardInterrupt):
print '\n exception handled'
print 'Clean Exit on Ctrl-C/D'
- Tkinter - it allows to stop looping on event as "button pressed":
from Tkinter import *
Var = 1
def __init__(self, master):
frame = Frame(master)
self.button = Button(frame, text="QUIT",
self.stoploop = Button(frame, text="Stop",
while self.Var == 1:
print "\nClean exit from the loop"
self.Var = 0
print "Var = %d" % self.Var
root = Tk()
app = App(root)
- Loop in a separate thread (similar to Tkinter variant) - I came up with this idea before finding other better solutions: if the loop is running in a separate thread then user still has access to the main program from keyboard and hence can control the loop too:
import threading, timeA disadvantage of this approach is that the loop thread can not use the terminal window since the main program needs it for input from a user. If it is about logging information in the loop - then the info should be saved into a file, for example.
class LoopThread (threading.Thread):
Value = 0
Counts = 0
print 'Loop is started'
while self.Value != 10:
self.Counts = self.Counts + 1
print 'Loop was ended, Counts %d' % self.Counts
def setVal(self, Val):
self.Value = Val
# Create the object
MyLoop = LoopThread()
# Start the thread
# Send the loop termination value from
# the main program whenever you need