如何在 python 中按下某个键时停止程序?

How to stop a program when a key is pressed in python?

我有一个无限循环的程序,每 5 秒打印一次 "program running",我想在按下结束键时停止它。

所以我创建了一个按键侦听器,如果按下结束键,则 returns 为 false。如果我没有无限循环,那应该可以工作。我希望它即使在我处于无限循环中时也能正常工作。

这是我的代码:

from pynput import keyboard
import time
def on_press(key):
    print key
    if key == keyboard.Key.end:
        print 'end pressed'
        return False        
with keyboard.Listener(on_press=on_press) as listener:
    while True:
        print 'program running'
        time.sleep(5)
    listener.join()
from pynput import keyboard
import time

break_program = False
def on_press(key):
    global break_program
    print (key)
    if key == keyboard.Key.end:
        print ('end pressed')
        break_program = True
        return False

with keyboard.Listener(on_press=on_press) as listener:
    while break_program == False:
        print ('program running')
        time.sleep(5)
    listener.join()