I have a python program which uses various Bash shell scripts. However, some of them require (y/n) input. I know the input required based on the question number so it's a matter of being able to provide that automatically.
Is there a way in Python to do that?
As a last resort I can send a signal to a window etc. but I'd rather not do that.
2 Answers 2
Probably the the easiest way is to use pexpect. An example (from the overview in the wiki):
import pexpect
child = pexpect.spawn('ftp ftp.openbsd.org')
child.expect('Name .*: ')
child.sendline('anonymous')
child.expect('Password:')
child.sendline('[email protected]')
child.expect('ftp> ')
child.sendline('cd pub')
child.expect('ftp> ')
child.sendline('get ls-lR.gz')
child.expect('ftp> ')
child.sendline('bye')
If you don't want to use an extra module, using subprocess.Popen is the way to go, but it is more complicated. First you create the process.
import subprocess
script = subprocess.Popen(['script.sh'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, shell=True)
You can either use shell=True here, or prepend the name of the shell to the command arguments. The former is easier.
Next you need to read from script.stdout until you find your question number. Then you write the answer to script.stdin.
3 Comments
shell=True is considered unsafe.Use subprocess.Popen.
from subprocess import Popen, PIPE
popen = Popen(command, stdin=PIPE)
popen.communicate('y')