Search code examples
pythonloopsubuntuwhile-loopinfinite

Pause an infinite while loop with a single keypress


I'm new to python and I have been trying to find a simple way to pause an operating while-loop, making it possible to start it again from where it was paused. I have searched on Google for help and tips, but everything I find seems very complex. Is there a simple way to do this?

I've read that you can use termios and tkinter.

I'm using ubuntu.


Solution

  • Here's a simple tkinter program that runs in an infinite loop. Pressing space pauses/unpauses it, and pressing Esc quits.

    Note: The following is for Python 2.x, if you're using Python 3, change Tkinter in the first line to tkinter (lower case t).

    from Tkinter import *
    import time
    
    class MyLoop():
        def __init__(self, root):
            self.running = True
            self.aboutToQuit = False
            self.root = root
            self.someVar = 0
            self.root.bind("<space>", self.switch)
            self.root.bind("<Escape>", self.exit) 
    
            while not self.aboutToQuit:
                self.root.update() # always process new events
    
                if self.running:
                    # do stuff
                    self.someVar += 1
                    print(self.someVar)
                    time.sleep(.1)
    
                else: # If paused, don't do anything
                    time.sleep(.1)
    
        def switch(self, event):
            print(['Unpausing','Pausing'][self.running])
            self.running = not(self.running)
    
        def exit(self, event):
            self.aboutToQuit = True
            self.root.destroy()
    
    if __name__ == "__main__":
        root = Tk()
        root.withdraw() # don't show the tkinter window
        MyLoop(root)
        root.mainloop()
    

    This is a possible output, where I manually paused and unpaused the program twice before I quit.

    1
    2
    3
    4
    5
    6
    7
    Pausing
    Unpausing
    8
    9
    10
    11
    12
    13
    14
    15
    16
    Pausing
    Unpausing
    17
    18
    19
    20
    21
    22
    23
    24
    25