简单PythonPause/Resume

Simple Python Pause/Resume

我正在尝试 pause/resume 使用热键的任务,编写了下面的程序,在按下暂停热键时运行正常,但恢复不工作。我想我犯了一些逻辑错误,需要您的专家建议来克服它。这是我写的脚本

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

试试这个

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