简体   繁体   中英

Python input with pynput listener

I am looking for a way to have some manual optional input.

thanks to MaLiN2223 for suggesting a key listener.

What I'm trying to do is capture keyboard input to trigger another action.

Trying to use pynpu below, I've added a print so we can see how each key press is interpretted. I can't figure out how to get the listener to capture "regular" keyboard inputs, like numbers or letters. We can see from the output the listener is working but only recognizing when I press "special" keys, such as Shift, control, etc.

I'd like to be able to type something like "1" and hit enter, I'd expect the output to include "place 1" as per the code below.

Its worth noting I'm running on a mac.

from pynput import keyboard

def on_press(key):
    try:
        print('place 1')
    except AttributeError:
        print('place 2')
        print('special key {0} pressed'.format(
            key))

def on_release(key):
    print('place 3')
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        print('place 4')
        # Stop listener
        return False

# Collect events until released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

and the output is this. As you can see, nothing happens when I type numbers and hit enter. If I press a special key, the program reacts as appropriate.

1
2
3
4
place 1
place 3
Key.shift released
place 1
place 3
Key.ctrl released
place 1
^Z

According to your comment I would use some kind of key listener. You can install pynput package and use the functions to see what user typed. The main idea would be this:

from pynput import keyboard
input = ""
expected = "expected"
def on_press(key):
    try:
        input +=key.char
        if input == expected:
            do_something()
            input = ""
    except AttributeError:
        #handle special key
with keyboard.Listener(on_press=on_press) as listener:
    listener.join()

The above code will call do_something function after user typed 'expected'.

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