Search code examples
pythonlinuxinterruptkeyboardinterrupt

How can we generate Keyboard interrupts using python


Is there a way to generate Keyboard interrupt without actually pressing a key on keyboard using a python program in linux. The interrupt should look like if someone has pressed a key on the keyboard and the complete system should get that interrupt irrespective of the currently focused window. For example if I have opened an editor and my python program generates an interrupt for key "A", then "A" should get printed in the editor.


Solution

  • python-uinput

    Here is the example:

    import uinput
    
    device = uinput.Device([
            uinput.KEY_E,
            uinput.KEY_H,
            uinput.KEY_L,
            uinput.KEY_O,
            ])
    
    device.emit_click(uinput.KEY_H)
    device.emit_click(uinput.KEY_E)
    device.emit_click(uinput.KEY_L)
    device.emit_click(uinput.KEY_L)
    device.emit_click(uinput.KEY_O)