简体   繁体   中英

Returning an argument on key press detection using Pynput

 from pynput.keyboard import Listener import time def on_press(key, run): # The function that's called when a key is pressed print( run) print("Key pressed: {0}".format(key)) if 'char' in dir(key): #check if char method exists, if key.char == 'q': print("quit") run = False run = True listener = Listener(on_press=lambda event: on_press(event, run=run)) listener.start() while run: print("do things here") time.sleep(2) #stop the listener... listener.stop()

I have a simple thing to do with Pynput which I have just discovered. Basically want to do 'things (basically running LEDs)' but listen out for a keyboard input (eg q for quit) which then stops the 'things'. Ive got this far but cant seem to get 'q' to stop it. Is there an easy way to fix it or even a better way of doing it?

The problem is that you are not modifying the run variable in the function, when you set it to false. You are modifying a different variable also called run that only exists in the function and is not the same as the variable that you declared in your code. This has to to with the scope of variables. The run variable declared outside the function exists in the global scope and the variable inside the function exists in the local scope of the function. If a variable is declared inside the scope of afunction with the same name as a variable in the global scope, every reference to the variable name inside the function points to the variable declared in the local scope.

The easiest way to fix that is to make the run variable declared in your global scope global in the scope of the function.

from pynput.keyboard import Listener
import time

def on_press(key):  # The function that's called when a key is pressed
    global run
    print("Key pressed: {0}".format(key))
    if 'char' in dir(key):     #check if char method exists,
        if key.char == 'q':
            print("quit")
            run = False

run = True
listener = Listener(on_press=lambda event: on_press(event))
listener.start()

while run:
    print("do things here")
    time.sleep(2)
    
#stop the listener...
listener.stop()

Thats it, youve got it: Realised I also then didnt need to pass any arguements so simplified this even more as below:

 from pynput.keyboard import Listener import time def on_press(key): # The function that's called when a key is pressed global run print( run) print("Key pressed: {0}".format(key)) if 'char' in dir(key): #check if char method exists, if key.char == 'q': print("quit") run = False run = True listener = Listener(on_press=on_press) listener.start() while run: print("do things here") time.sleep(2) #stop the listener... listener.stop()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM