6

I want to write a script that always listens in the background and executes a particular command when the user hits a specific key combination such as Alt + N. How this can be done?

1
  • 1
    I see the command-line tag on this, but if you are using a gui or a terminal window inside a gui (now or some other time), check out AutoKey. It will allow you to easily define many hotkeys which can trigger anything from a simple text phrase substitution to the execution of an arbitrarily complex macro written in Python. It outputs keystrokes to the gui/terminal just as if you typed it. It also has a number of other features and is very powerful, yet easy to use. A fairly recent version is included in the Ubuntu repos. For info, see code.google.com/p/autokey . (migrating to GitHub)
    – Joe
    Mar 22, 2015 at 22:03

1 Answer 1

7

Download the following python module: showkey.py

Then create a python script (let's call it test.py):

#!/usr/bin/env python

from showkey import ShowKey

def alt_n(arg):
    print "Alt N was pressed"

sk = ShowKey()
sk.addKeyAction([49, 56], alt_n)    # adds handler for Alt-N comb.
sk.run()

Put showkey.py in your PYTHONPATH or put both test.py and showkey.py in the same folder.

Run your python script this way:

sudo ./test.py

The alt_n() callback will be triggered when the user hits the Alt + N combination. Adapt the handler content for your needs.

To know the keycodes (the same codes used by the showkey command) to use with showkey.py, just run it as a script again with sudo. All keypress events will be printed in your terminal.

$ sudo ./showkey.py 
Current terminal mode: OFF
Key pressed - keycode: 28
Key pressed - keycode: 56
[...]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .