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

北战南征 提交于 2021-01-21 05:49:48

问题


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.

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.

Here's my code:

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

回答1:


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


来源:https://stackoverflow.com/questions/49550355/how-to-stop-a-program-when-a-key-is-pressed-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!