I'm trying to get the keyboard code of a character pressed in python. For this, I need to see if a keypad number is pressed.
This is not what I'm looking for:
import tty, sys
tty.setcbreak(sys.stdin)
def main():
tty.setcbreak(sys.stdin)
while True:
c = ord(sys.stdin.read(1))
if c == ord('q'):
break
if c:
print c
which outputs the ascii code of the character. this means, i get the same ord for a keypad 1 as as a normal 1.
I've also tried a similar setup using the curses
library and raw
, with the same results.
I'm trying to get the raw keyboard code. How does one do this?
As synthesizerpatel said, I need to go to a lower level.
Using pyusb:
import usb.core, usb.util, usb.control
dev = usb.core.find(idVendor=0x045e, idProduct=0x0780)
try:
if dev is None:
raise ValueError('device not found')
cfg = dev.get_active_configuration()
interface_number = cfg[(0,0)].bInterfaceNumber
intf = usb.util.find_descriptor(
cfg, bInterfaceNumber=interface_number)
dev.is_kernel_driver_active(intf):
dev.detach_kernel_driver(intf)
ep = usb.util.find_descriptor(
intf,
custom_match=lambda e: usb.util.endpoint_direction(e.bEndpointAddress) == usb.util.ENDPOINT_IN)
while True:
try:
# lsusb -v : find wMaxPacketSize (8 in my case)
a = ep.read(8, timeout=2000)
except usb.core.USBError:
pass
print a
except:
raise
This gives you an output: array('B', [0, 0, 0, 0, 0, 0, 0, 0])
array pos: 0: AND of modifier keys (1 - control, 2 - shift, 4 - meta, 8 - super) 1: No idea 2 -7: key code of keys pushed.
so:
[3, 0 , 89, 90, 91, 92, 93, 94]
is:
ctrl+shift+numpad1+numpad2+numpad3+numpad4+numpad5+numpad6
If anyone knows what the second index stores, that would be awesome.
To get raw keyboard input from Python you need to snoop at a lower level than reading stdin.
For OSX check this answer:
OS X - Python Keylogger - letters in double
For Windows, this might work:
http://www.daniweb.com/software-development/python/threads/229564/python-keylogger
monitor keyboard events with python in windows 7
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With