Simulating Key Press event using Python for Linux

Have a look at this https://github.com/SavinaRoja/PyUserInput its cross-platform control for mouse and keyboard in python

Keyboard control works on X11(linux) and Windows systems. But no mac support(when i wrote this answer).

from pykeyboard import PyKeyboard
k = PyKeyboard()

# To Create an Alt+Tab combo
k.press_key(k.alt_key)
k.tap_key(k.tab_key)
k.release_key(k.alt_key)

A more low-level approach would be to create an uinput device from which you would then inject input events into the linux input subsystem. Consider the following libraries:

  • python-uinput
  • evdev

Example of sending <enter> with the latter:

from evdev import uinput, ecodes as e

with uinput.UInput() as ui:
     ui.write(e.EV_KEY, e.KEY_ENTER, 1)
     ui.write(e.EV_KEY, e.KEY_ENTER, 0)
     ui.syn()

If the "model" is running graphically (with the X window system), the already-suggested xsendkey is a possibility, or xsendkeycode. If it's running textually (in a terminal window), then pexpect.