Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a cross-platform python low-level API to capture or generate keyboard events?

I am trying to write a cross-platform python program that would run in the background, monitor all keyboard events and when it sees some specific shortcuts, it generates one or more keyboard events of its own. For example, this could be handy to have Ctrl-@ mapped to "my.email@address", so that every time some program asks me for my email address I just need to type Ctrl-@.

I know such programs already exist, and I am reinventing the wheel... but my goal is just to learn more about low-level keyboard APIs. Moreover, the answer to this question might be useful to other programmers, for example if they want to startup an SSH connection which requires a password, without using pexpect.

Thanks for your help.

Note: there is a similar question but it is limited to the Windows platform, and does not require python. I am looking for a cross-platform python api. There are also other questions related to keyboard events, but apparently they are not interested in system-wide keyboard events, just application-specific keyboard shortcuts.

Edit: I should probably add a disclaimer here: I do not want to write a keylogger. If I needed a keylogger, I could download one off the web a anyway. ;-)

like image 599
MiniQuark Avatar asked Mar 24 '09 09:03

MiniQuark


1 Answers

There is no such API. My solution was to write a helper module which would use a different helper depending on the value of os.name.

On Windows, use the Win32 extensions.

On Linux, things are a bit more complex since real OSes protect their users against keyloggers[*]. So here, you will need a root process which watches one of[] the handles in /dev/input/. Your best bet is probably looking for an entry below /dev/input/by-path/ which contains the strings "kbd" or "keyboard". That should work in most cases.

[*]: Jeez, not even my virus/trojan scanner will complain when I start a Python program which hooks into the keyboard events...

like image 88
Aaron Digulla Avatar answered Sep 25 '22 05:09

Aaron Digulla