3

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

3

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.

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

3 Comments

shell=True is considered unsafe.
Almost. It is unsafe with untrusted input. But the alternative of prepending the name of the shell to the args list is equally unsafe in that case. If you want to run a shell script, you're going to have to use a shell...
Note that some password prompts will bypass stdin to read directly from the controlling terminal. In those cases, you can't give them the password with a pipe, but it's still possible using pexpect.
3

Use subprocess.Popen.

from subprocess import Popen, PIPE


popen = Popen(command, stdin=PIPE)
popen.communicate('y')

2 Comments

This answer won't work it its current form, since you also have to read the "question number" from the process's standard output.
If that's so, then one must do nasty pipe rw.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.