3

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

因此,我创建了一个键侦听器,如果按下结束键则返回 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()
4

1 回答 1

8
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()
于 2018-03-29T07:51:55.727 回答