Masoud Rahimi
Masoud Rahimi

Reputation: 6051

Detect keyboard input with support of Unicode in python

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 that uses Unicode characters and I want to detect them.

IMPORTANT: I need the 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()

Upvotes: 3

Views: 4225

Answers (3)

ilon
ilon

Reputation: 179

Alternative to pynput that works also over ssh: sshkeyboard. Install with pip install sshkeyboard,

then write script such as:

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

And it will print:

'a' pressed
'a' released

When A key is pressed. ESC key ends the listening by default.

Upvotes: 0

Masoud Rahimi
Masoud Rahimi

Reputation: 6051

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

Upvotes: 1

Francis Potter
Francis Potter

Reputation: 1639

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.

Upvotes: 2

Related Questions