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

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

问题描述:

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

I have a program that is an endless loop that prints "program running" every 5 seconds and I want to stop it when I press the end key.

因此,我创建了一个键侦听器,如果按下结束键,该侦听器将返回 false.如果我没有无限循环,那应该可行.我希望它即使在无限循环中也能工作.

So I created a key listener that returns false if the end key is pressed. That should work if I won't have the endless loop. And I want it to work even when I'm in the endless loop.

这是我的代码:

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