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

Detect keyboard input with support of Unicode in python

我想检测 python 代码中的击键。我已经用不同的库尝试了很多方法,但它们都无法检测到 UTF 键盘输入,只能检测到 Ascii。例如,我想在用户键入这些键时检测 Unicode 字符,如 ("د") 或 ("⁄")。这意味着如果我按 Alt+Shift,它会将我的输入更改为另一种使用 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()

很大程度上取决于操作系统和键盘输入方法,但这适用于我的 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.

这里是代码里面returnsUnicode的个数。它无法检测当前语言,并且始终显示旧语言,但仅在 cmd window 本身中显示,如果您专注于任何其他 window,它会完美显示当前的 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()

也可以在 ssh 上运行的 pynput 替代方法: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键默认结束监听