Simulating Key Press event using Python for Linux

限于喜欢 提交于 2019-11-26 08:19:17

问题


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!


回答1:


If the "model" is running graphically (with the X window system), the already-suggested xsendkey is a possibility, or xsendkeycode. If it's running textually (in a terminal window), then pexpect.




回答2:


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)



回答3:


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



回答4:


http://people.csail.mit.edu/adonovan/hacks/xsendkey.html




回答5:


I recommend PyAutoGui. It's ridiculously simple to use, it's cross-platform and it's for Python 3 and 2.

In the linked page are listed the dependences and some code examples.



来源:https://stackoverflow.com/questions/2575528/simulating-key-press-event-using-python-for-linux

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!