Simulate keystroke in Linux with Python Simulate keystroke in Linux with Python python python

Simulate keystroke in Linux with Python


Consider python-uinput and evdev. Example of shift+a with the latter:

from evdev import uinput, ecodes as ewith uinput.UInput() as ui:    ui.write(e.EV_KEY, e.KEY_LEFTSHIFT, 1)    ui.write(e.EV_KEY, e.KEY_A, 1)    ui.syn()


python-uinput:

Pythonic API to Linux uinput kernel module...

Python-uinput is Python interface to Linux uinput kernel module which allows attaching userspace device drivers into kernel. In practice, Python-uinput makes it dead simple to create virtual joysticks, keyboards and mice for generating arbitrary input events programmatically...


Although it's specific to X, you can install the xautomation package (apt-get install xautomation on Debian-based systems) and use xte to simulate keypresses, e.g.:

from subprocess import Popen, PIPEcontrol_f4_sequence = '''keydown Control_Lkey F4keyup Control_L'''shift_a_sequence = '''keydown Shift_Lkey Akeyup Shift_L'''def keypress(sequence):    p = Popen(['xte'], stdin=PIPE)    p.communicate(input=sequence)keypress(shift_a_sequence)keypress(control_f4_sequence)