11

I want to automatize upgrade of a program.

I run in Python this code:

import subprocess
subprocess.call('./upgrade')

When I do this, I get output from shell that Upgrade procedure started successfully, and then I get 'Press Enter to continue'. How would I automatize this process, so that python script automatically "presses" enter when promted? I need this to be done twice during procedure. I need this to be done on Linux, not Windows, as it was asked here: Generate keyboard events Also, this needs to be done specifically after Shell prompts for Enter. Thanks for any help. I did not find solution here: Press enter as command input

Community
  • 1
  • 1
Zvonimir Peran
  • 701
  • 5
  • 9
  • 16

1 Answers1

17

You can use subprocess.Popen and subprocess.communicate to send input to another program.

For example, to send "enter" key to the following program test_enter.py:

print "press enter..."
raw_input()
print "yay!"

You can do the following:

from subprocess import Popen, PIPE
p = Popen(['python test_enter.py'], stdin=PIPE, shell=True)
p.communicate(input='\n')

You may find answer to "how do i write to a python subprocess' stdin" helpful as well.

Community
  • 1
  • 1
Julia Schwarz
  • 2,610
  • 1
  • 19
  • 25
  • 5
    Quote from the subprocess module (python 3) regarding `input`: `if self.universal_newlines is True, this should be a string; if it is False, "input" should be bytes`. So: `input=b'\n'` – user136036 Jan 04 '18 at 02:33
  • comment this for myself and other people who maybe have met this problem. When I use `Popen` but not `call`, the `communicate` API will be blocked or timeout, and then according to the official doc, it said: Note that if you want to send data to the process’s stdin, you need to create the Popen object with `stdin=PIPE` after I add this in my code, it works. – Kevin Liu Aug 27 '21 at 07:53
  • `Argument "input" to "communicate" of "Popen" has incompatible type "str"; expected "Optional[bytes]"mypy(error)` (just a warning) – Sterling Mar 26 '22 at 22:45