Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate keystroke in Linux with Python

How can I simulate a keystroke in python? I also want to press multiple keys simultaneously.

Something like:

keystroke('CTRL+F4')

or

keystroke('Shift+A')
like image 365
microo8 Avatar asked Apr 19 '11 09:04

microo8


People also ask

Can Python simulate keypress?

This demonstrates how to press keys with Python. Using pynput we are able to simulate key presses into any window. This will show you how to press and release a key, type special keys and type a sentence.

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.


4 Answers

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

from evdev import uinput, ecodes as e

with uinput.UInput() as ui:
    ui.write(e.EV_KEY, e.KEY_LEFTSHIFT, 1)
    ui.write(e.EV_KEY, e.KEY_A, 1)
    ui.syn()
like image 178
gvalkov Avatar answered Sep 23 '22 19:09

gvalkov


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...

like image 44
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 19:09

Ignacio Vazquez-Abrams


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, PIPE

control_f4_sequence = '''keydown Control_L
key F4
keyup Control_L
'''

shift_a_sequence = '''keydown Shift_L
key A
keyup Shift_L
'''

def keypress(sequence):
    p = Popen(['xte'], stdin=PIPE)
    p.communicate(input=sequence)

keypress(shift_a_sequence)
keypress(control_f4_sequence)
like image 21
Mark Longair Avatar answered Sep 25 '22 19:09

Mark Longair


If you plan to use it on Linux, try pyautogui library. For multiple keys you will need to use hotkey, e.g.:

pyautogui.hotkey('ctrl', 'c')  # ctrl-c to copy

For me it worked - see here: How to pass a keystroke (ALT+TAB) using Popen.communicate (on Linux)?

like image 37
michalrudko Avatar answered Sep 23 '22 19:09

michalrudko