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')
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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()
Method 2
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)
Method 3
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…
Method 4
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)?
Method 5
If you are on Windows, use Sendkeys and if on Linux, try out the suggestion given here for xsendkeys or pexpect.
Method 6
Simplest solution I have found was using pynput. You could do the following:
from pynput.keyboard import Key, Controller keyboard = Controller() with keyboard.pressed(Key.ctrl): keyboard.press(Key.f4) keyboard.release(Key.f4)
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0