使用Python检测支持Unicode的键盘输入

3
我希望能在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()
3个回答

2
很多情况取决于操作系统和键盘输入方法,但在我的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


1
谢谢,但我需要一个Windows代码。在Windows中,“tty”和“termios”不起作用。 - undefined
有关Windows解决方案的任何建议? - undefined

1

这里是返回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()

不,这似乎不起作用。 - undefined

0

一个可以在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 键结束监听。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接