microo8 microo8 - 5 months ago 160
Linux Question

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')

Answer

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)