Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating Key Press event using Python for Linux

I am writing a script to automate running a particular model. When the model fails, it waits for a user input (Enter key). I can detect when the model has failed, but I am not able to use python (on linux) to simulate a key press event. Windows has the SendKeys library to do this but I was wondering if there is a similar library for python on linux.

Thanks!

like image 754
user308827 Avatar asked Apr 04 '10 18:04

user308827


People also ask

Can Python simulate keyboard input?

Use the input() function to get Python user input from keyboard. Press the enter key after entering the value. The program waits for user input indefinetly, there is no timeout. The input function returns a string, that you can store in a variable.

How do you simulate keystrokes?

To simulate native-language keystrokes, you can also use the [Xnn] or [Dnn] constants in the string passed to the Keys method. nn specifies the virtual-key code of the key to be “pressed”. For instance, [X221]u[X221]e will “type” the u and e characters with the circumflex accent.


2 Answers

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)
like image 100
naren Avatar answered Oct 01 '22 07:10

naren


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()
like image 36
gvalkov Avatar answered Oct 01 '22 07:10

gvalkov