使用热键打破循环

Break loop using hotkey

有数百个类似的问题,但其中 none 似乎是我的解决方案。 我的代码是这样形成的

def iterative_func():
    # do things
while True:
    iterative_func()

然后我希望它在我按下热键时停止,比方说 'ctrl+k'。 我试过 pynput 但监听器不适用,因为它等待输入,而脚本的其余部分 (iterative_func()) 不会 运行,在我的情况下,脚本应该连续 运行 直到我按下某个热键。 还有解决方案

while True:
    try:
        iterative_func()
    except KeyboardInterrupt:
        break

对我不起作用(我不知道为什么,但也许是因为我运行宁VSCode),反正这不是我想要实现的代码,因为脚本将作为 .exe 文件部署。

PS。 我无法从 pynput 导入 KeyController,它提示错误,我不知道如何解决这个问题,所以也应该避免使用这些解决方案。

I tried pynput but the listener is not applicable since it waits for an Input and the rest of the script (iterative_func()) won't run

我可以阐明如何克服这个让你选择退出的问题 pynput。请参阅以下方法:

from pynput import keyboard

running = True  # flag on loop runs


def stop_run():  # function to stop the program
    global running
    running = False


# register a hotkey, and call stop_run() when it is pressed
with keyboard.GlobalHotKeys({'<ctrl>+k': stop_run}) as h:
    while running:
        print("Running ... ")

这将 运行 您的代码并等待热键通过标志停止循环。