简体   繁体   English

使用Pynput侦听器的Python输入

[英]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. 感谢MaLiN2223建议主要听众。

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. 在下面尝试使用Pynpu时,我添加了打印件,以便我们可以看到每个按键的解释方式。 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. 从输出中我们可以看到侦听器正在工作,但是只有在按下“特殊”键(例如Shift,control等)时才能识别出。

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. 我希望能够输入“ 1”之类的内容,然后按Enter键,我希望输出按照以下代码包含“ place 1”。

Its worth noting I'm running on a mac. 值得注意的是,我在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. 如您所见,当我键入数字并按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. 您可以安装pynput软件包并使用这些功能查看用户输入的内容。 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'. 在用户键入“ expected”之后,以上代码将调用do_something函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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