Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make python script press 'enter' when prompted on Shell

Tags:

python

linux

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

like image 280
Zvonimir Peran Avatar asked Jul 21 '15 09:07

Zvonimir Peran


1 Answers

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.

like image 76
Julia Schwarz Avatar answered Oct 29 '22 14:10

Julia Schwarz