在Python中的Unicode支持下检测键盘输入



我想检测python代码中的键。我已经尝试了许多具有不同库的方法,但是它们都无法检测到UTF键盘输入,而仅检测ASCII。例如,如果用户输入这些键,我想检测("€")或("ۼ")等Unicode字符。这意味着,如果我按Alt 移动,则将我的输入更改为使用Unicode字符的另一种语言,我想检测它们。

重要:我需要Windows版本。

它必须检测到击键甚至不专注于终端。

假设这个简单的示例:

from pynput import keyboard
def on_press(key):
    try:
        print(key.char)
    except AttributeError:
        print(key)
if __name__ == "__main__":
    with keyboard.Listener(on_press=on_press) as listener:
            listener.join()

这是返回Unicode数量的代码。它无法检测到当前语言,并且总是显示旧语言,但仅在CMD窗口本身中,如果您专注于任何其他窗口,它将完美地显示当前的Unicode编号。

from pynput import keyboard
def on_press(key):
    if key == keyboard.Key.esc:
        listener.stop()
    else:
        print(ord(getattr(key, 'char', '0')))
controller = keyboard.Controller()
with keyboard.Listener(
        on_press=on_press) as listener:
    listener.join()

很大程度上取决于操作系统和键盘输入方法,但这在我的Ubuntu系统上起作用;我用一些西班牙字符测试。

import sys
import tty
import termios
def getch():
    fd = sys.stdin.fileno()
    old_settings = termios.tcgetattr(fd)
    try:
        tty.setraw(fd)
        ch = sys.stdin.read(1)
    finally:
        termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
    return ch
x = getch()
print("You typed: ", x, " which is Unicode ", ord(x))

这是英语与西班牙语中的相同击键:

$ python3 unicode-keystroke.py
You typed:  :  which is Unicode  58
$ python3 unicode-keystroke.py
You typed:  Ñ  which is Unicode  209

Getch功能来自ActiveState。

替代pynput的替代方法也可以通过ssh:sshkeyboard。使用pip install sshkeyboard安装

然后编写脚本,例如:

from sshkeyboard import listen_keyboard
def press(key):
    print(f"'{key}' pressed")
def release(key):
    print(f"'{key}' released")
listen_keyboard(
    on_press=press,
    on_release=release,
)

它将打印:

'a' pressed
'a' released

当按下 a 键时。 esc 键默认结束听力。

最新更新