Keyboard input as Unicode characters in python

耗尽温柔 提交于 2019-12-08 11:00:08

问题


I want to detect keystrokes in python code. I already try a lot of methods with different libraries but all of them cant detect the UTF keyboard input and only detect Ascii. For example, I want to detect Unicode characters like ("د") or ("ۼ") if a user typed these keys. It means that if I press Alt+Shift it changes my input to another language which uses Unicode characters and I want to detect them.

IMPORTANT: I need Windows version.

It must detect keystrokes even not focusing on the terminal.

Suppose this simple example:

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()

回答1:


Here is the code which returns the number of Unicode. It cannot detect the current language and always shows the old one but only in cmd window itself and if you focus on any other window it shows the current Unicode number perfectly.

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()



回答2:


A lot depends on the operating system and keyboard entry method, but this works on my Ubuntu system; I tested with some Spanish characters.

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))

Here's the same keystroke in English vs. Spanish:

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

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

The getch function is from ActiveState.



来源:https://stackoverflow.com/questions/46271690/keyboard-input-as-unicode-characters-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!