1

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?

serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76

2 Answers2

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

Brian
  • 2,172
  • 14
  • 24
0

So, here is my final solution (based on the previous answer and using python-uinput). It uses the ability to type Unicode symbols by pressing Ctrl+Shift+U then typing the hex code of the symbol.

Here is the Python script I wrote for it:

import uinput, time

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)))
serge1peshcoff
  • 4,342
  • 11
  • 45
  • 76