Paste a string into selected text field in Gnome using Python

时间:2016-02-12 19:24:28

标签: python events keyboard clipboard keypress

I need to write a Python script to paste a defined string into selected text field inside current executed program (don't change the source of the program). It should behave like I've pressed the key on keyboard.

I've seen this Python simulate keydown, and eventually this is the thing I want to do, but the problem is the characters I want to type in are not in the standard keyboard layout.

So, is there any way to accomplish this?

2 个答案:

答案 0 :(得分:1)

You might want to look at uinput. It allows you to inject keystrokes, buttons, mouse movements, joystick movements, etc through the /dev/uinput device.

In Python, you'd do something like:

keys = [uinput.KEY_X, uinput.KEY_Y, uinput.KEY_Z]
device = uinput.Device(keys)

...

# Simulate key Y being pressed.
device.emit(uinput.KEY_Y, 1)

You'll need to get uinput, of course:

pip install python-uinput

And you may need to install uinput device if you don't have.

(Well, this is only a solution for Linux, I suspect, and unfortunately, I didn't ask what's your platform).

答案 1 :(得分:0)

所以,这是我的最终解决方案(基于之前的答案并使用python-uinput)。它可以通过按Ctrl + Shift + U然后键入符号的十六进制代码来键入Unicode符号。

这是我为它写的Python脚本:

导入uinput,时间

allKeys = [uinput.KEY_LEFTSHIFT, uinput.KEY_LEFTCTRL, uinput.KEY_SPACE, uinput.KEY_U,
          uinput.KEY_A, uinput.KEY_B, uinput.KEY_C, uinput.KEY_D,
          uinput.KEY_E, uinput.KEY_F, uinput.KEY_0, uinput.KEY_1,
          uinput.KEY_2, uinput.KEY_3, uinput.KEY_4, uinput.KEY_5,
          uinput.KEY_6, uinput.KEY_7, uinput.KEY_8, uinput.KEY_9]

device = uinput.Device(allKeys)

sleepInterval = 0.003

def printChar(charCode):
  time.sleep(sleepInterval)
  device.emit(uinput.KEY_LEFTSHIFT, 1);
  device.emit(uinput.KEY_LEFTCTRL, 1);
  device.emit_click(uinput.KEY_U);
  device.emit(uinput.KEY_LEFTSHIFT, 0);
  device.emit(uinput.KEY_LEFTCTRL, 0);
  time.sleep(sleepInterval)

  for symbol in charCode:
    device.emit_click(uinput._chars_to_events(symbol)[0]);
    time.sleep(sleepInterval)

  device.emit_click(uinput.KEY_SPACE);
  time.sleep(sleepInterval)

charString = "string that will be typed"
for char in charString:
  printChar('{:04x}'.format(ord(char)))