I have a python script that before running it asks you for a couple of user typed options that need to be set. What I was wondering is is it possible to make a bash script that auto fills in the options as defined in the bash script for me?
-
I will work on it. I am on mobile right now, thanks for the note though. – Nov 12 '12 at 14:35
2 Answers
Try something like this:
echo -n 'First answer\nSecond answer\n' | python script.py
For more demanding tasks, use expect.

- 10,999
- 13
- 68
- 158
-
I will try when I get home, thank you! Just on a long shot, anyone know of a batch version of that command? – Nov 12 '12 at 14:38
-
1That won't work as long the receivin script can't read from stdin. Commandline arguments and pipes are two different concepts. see http://stackoverflow.com/a/1504919/1107807 . But you could do a: `python script $(echo -n 'First answer\nSecond answer\n')` – Don Question Nov 12 '12 at 14:42
-
2There is a pure-python expect implementation: [pexpect](http://www.noah.org/wiki/pexpect). – Martijn Pieters Nov 12 '12 at 14:46
-
1You can also use [Expect-Lite](http://expect-lite.sourceforge.net/) if this method fails. – Nov 12 '12 at 22:41
I think what you're looking for is Expect-lite (http://expect-lite.sourceforge.net). It's a simple scripting language that will easily automate passing in responses to cli programs. It's pretty light weight and will allow you to write a script that will run your python program.
For example, if you wanted to automate password login over ssh with it you'd write something like this:
>ssh root@host-021
<assword:
>>secret_password
# issue a command once logged in
>ls
>exit
However the output can be a bit messy. Instead you can use the Python module pexpect (http://www.noah.org/wiki/pexpect) which will let you write a simple python script to run the other python script while automatically responding to the prompts.
The same example from above would then become:
child = pexpect.spawn('ssh root@host-021')
child.expect('assword:')
child.sendline('secret_password')
child.sendline('ls')
child.sendline('exit')
This in turn would mask the output, but you can set a logfile to log the output. You can also set the logfile as STDOUT like so child.logfile = sys.stdout
.
There is much more you can do with it which might be useful to you, and is shown in the documentation.

- 544
- 3
- 16