3

I am trying to write a python script which will execute a bash command line program for me. This program asks for user input twice, and I want my script to automatically enter "1" each time.

I've heard of something like this:

os.system("program < prepared_input")

How do I write prepared_input? Thanks.

3 Answers 3

5

Create file with two lines:

1
1

And use read in the bash script to get the input:

Demo:

$ cat abc
1
1
$ cat so.sh
#!/bin/bash
read data
echo "You entered $data"
read data
echo "Now you entered $data"
$ bash so.sh <abc
You entered 1
Now you entered 1

Python :

>>> import os
>>> os.system("bash so.sh < abc")
You entered 1
Now you entered 1
0
Sign up to request clarification or add additional context in comments.

Comments

1

I suppose to make your example work you would need:

prepared_input = "<input goes here>"
os.system("program < {0}".format(prepared_input))

but depending on what you want to do, there are almost certainly better ways to achieve it. If you give us more information about what you're doing and why, we can perhaps suggest some alternatives.

1 Comment

are you sure that puts the "input goes here" actually works properly? I think it'll try to run what "input goes here" contains as a shell command instead
1

Use of pexpect will work for you...

Here is the solution - http://pypi.python.org/pypi/pexpect/

Comments

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.