7

I know that it's possible to send printable input to subprocesses by writeing to their stdin

from subprocess import, Popen, PIPE
proc = Popen([command, goes, here], stdin=PIPE)
proc.stdin.write("m")

How would I go about sending input such as arrow key presses, space, return, or backspace?

Inaimathi
  • 13,853
  • 9
  • 49
  • 93
  • Is there a specific command you are trying to run? – Nathan Villaescusa Oct 06 '12 at 01:52
  • @NathanVillaescusa - Specifically, I'm trying to run `omxplayer` as a subprocess and send it Left/Right/Up/Down arrows in order to seek. The rest of its interactive commands use printable characters. – Inaimathi Oct 06 '12 at 01:58

2 Answers2

9

I found someone who was trying to solve the opposite problem, create a program that could recognize the arrow keys: Recognizing arrow keys with stdin

I also found http://compgroups.net/comp.unix.programmer/how-to-send-up-arrow-key-to-popen-child/537480 which says:

"\x1B[A" for up
"\x1B[B" for down

So if \x1B is the escape character than you just append [A for up, [B for down, [C for right and [D for left and so on.

Take a look at http://en.wikipedia.org/wiki/ANSI_escape_sequences for a list of the different codes.

Community
  • 1
  • 1
Nathan Villaescusa
  • 17,331
  • 4
  • 53
  • 56
  • Yup, that did it. Out of curiosity, what did you search for? I came up empty after about 20 minutes of assorted googling for things like `python Popen send arrow keys`. – Inaimathi Oct 06 '12 at 02:13
  • 3
    I searched for "python handle stdin arrow keys" which led me to the stack overflow question and then "popen ansi escape" which led me to the other link. – Nathan Villaescusa Oct 06 '12 at 02:17
0

Try pyautogui library. For example:

pyautogui.hotkey('ctrl', 'c')  # ctrl-c to copy
pyautogui.press('enter')  # press the Enter key

More examples in the library webpage. For me it worked - see here.

michalrudko
  • 1,432
  • 2
  • 16
  • 30