Search code examples
pythonpython-3.xhotkeysresumepause

Simple Python Pause/Resume


I was trying to pause/resume a task using hotkey, wrote the program bellow which is working fine while hitting Pause hotkey, but resume is not working. I guess I did some logical errors and need your expert advice to overcome that. Here is the script I wrote

import keyboard


class Test:
    def __init__(self):
        self.run = True
        keyboard.add_hotkey("ctrl+alt+p", self.set_run)
        keyboard.add_hotkey("ctrl+alt+r", self.set_run_r)

    def set_run(self):
        self.run = False

    def set_run_r(self):
        self.run = True

    def start(self):
        val = 1
        while self.run:
            val += 1
            print("running ", val)

        keyboard.wait("esc")


Test().start()

Solution

  • Try this

    import keyboard
    import sys
    
    
    
    class Test:
        def __init__(self):
            self.val=1
            self.run = True
            keyboard.add_hotkey("ctrl+alt+p", self.set_run)
            keyboard.add_hotkey("ctrl+alt+r", self.set_run_r)
    
        def set_run(self):
            self.run = False
    
        def set_run_r(self):
            self.run = True
    
        def start(self):
            self.val += 1
            print(self.val)
            return
    
    
    test= Test()
    try:
            while True:
                if test.run:
                    test.start()
                else:
                    pass
    except KeyboardInterrupt:
         sys.exit()