How to convert a keycode to an char in python?

2019-08-10 22:24发布

问题:

I'm writing a program in Linux which reads and distinguish inputs from two USB devices(two barcode readers) which simulates a keyboard.

I've already can read inputs from USB, but it happens before OS translate keycode in a charactere.

For example, when I read 'a' i got 24, 'b' 25, etc....

For example, when I read 'a' i got 4, 'b' 5, etc....

Is there any way to convert that code in a char without manual mapping?

Some output exemples:

KEYPRESS = a output = array('B', [0, 0, 4, 0, 0, 0, 0, 0])

KEYPRESS = SHIFT + a output = array('B', [2, 0, 4, 0, 0, 0, 0, 0])

KEYPRESS = 1 output = array('B', [0, 0, 30, 0, 0, 0, 0, 0])

KEYPRESS = ENTER output = array('B', [0, 0, 81, 0, 0, 0, 0, 0])

thx!

回答1:

Use the chr function. Python uses a different character mapping (ASCII) from whatever you're receiving though, so you will have to add 73 to your key values to fix the offset.

>>> chr(24 + 73)
'a'
>>> chr(25 + 73)
'b'


回答2:

I've already can read inputs from USB, but it happens before OS translate keycode in a charactere. The problem seems to me in your interface or the driver program.

In ASCII 'a' is supposed to have ordinal value 97 whose binary representation is 0b1100001, where as what you are receiving is 27 whose binary representation is 0b11000, similarly for 'b' you were supposed to received '0b1100010' instead you received 25 which is 0b11001. Check your hardware to determine if the 1st and the 3rd bit is dropped from the input.

What you are receiving is USB scan code. I do not think there is a third party python library to do the conversion for you. I would suggest you to refer any of the USB Scan Code Table and from it, create a dictionary of USB Scan Code vs the corresponding ASCII.