使用 Python 在 Linux 中模拟击键

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5714072/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:42:47  来源:igfitidea点击:

Simulate keystroke in Linux with Python

pythonlinuxsimulationkeystroke

提问by microo8

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

如何在python中模拟击键?我也想同时按下多个键。

Something like:

就像是:

keystroke('CTRL+F4')

or

或者

keystroke('Shift+A')

采纳答案by Mark Longair

Although it's specific to X, you can install the xautomation package (apt-get install xautomationon Debian-based systems) and use xteto simulate keypresses, e.g.:

尽管它特定于 X,但您可以安装 xautomation 包(apt-get install xautomation在基于 Debian 的系统上)并用于xte模拟按键,例如:

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)

回答by Ignacio Vazquez-Abrams

python-uinput:

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

Pythonic API 到 Linux uinput 内核模块...

Python-uinput 是 Linux uinput 内核模块的 Python 接口,它允许将用户空间设备驱动程序附加到内核中。在实践中,Python-uinput 使得创建虚拟操纵杆、键盘和鼠标以编程方式生成任意输入事件变得非常简单......

回答by Senthil Kumaran

If you are on Windows, use Sendkeysand if on Linux, try out the suggestion given herefor xsendkeys or pexpect.

如果您使用的是 Windows,请使用Sendkeys;如果使用的是 Linux,请尝试此处针对 xsendkeys 或 pexpect给出的建议。

回答by gvalkov

Consider python-uinputand evdev. Example of shift+awith the latter:

考虑python-uinputevdevshift+a后者的例子:

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

回答by mrjoseph

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

如果您打算在 Linux 上使用它,请尝试使用pyautogui库。对于多个键,您需要使用热键,例如:

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

对我来说它有效 - 请参阅此处: How to pass a keystroke (ALT+TAB) using Popen.communicate (on Linux)?