2017-09-18 86 views
0

我想檢測python代碼中的擊鍵。我已經嘗試了很多使用不同庫的方法,但它們都不能檢測到UTF鍵盤輸入,只能檢測到Ascii。例如,如果用戶鍵入這些鍵,我想要檢測Unicode字符(如「د」)或(「ۼ」)。這意味着如果按下Alt + Shift鍵,它會將我的輸入更改爲使用Unicode字符的另一種語言,並且我想檢測它們。鍵盤輸入爲Python中的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() 

回答

0

以下是返回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() 
0

在很大程度上取決於操作系統和鍵盤輸入法,但是這個作品在我的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 

的殘培功能是從ActiveState

+0

謝謝,但我需要一個Windows代碼。在Windows'tty'和'termios'不工作。 –