12

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

2
  • possible duplicate of Press enter as command input Commented Jul 21, 2015 at 9:53
  • Use the expect module Commented Jul 21, 2015 at 10:01

1 Answer 1

18

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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'
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.
Argument "input" to "communicate" of "Popen" has incompatible type "str"; expected "Optional[bytes]"mypy(error) (just a warning)
Starting with Python 3, raw_input() was renamed to input(), besides print "" was replaced to print("") and add b before '\n'.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.