Bash script that handles multiple user inputs of python program

Question:

I have a python program that prompts for user input (via CLI) multiple times.

Just for example, let’s say I have a test.py file that prompts for input1, and then, some time after, input2:

...
...
input1 = input("Enter input 1")
...
...
input2 = input("Enter input 2")
...
...

How do I go about writing a bash script that runs this program, waits for and then gives the argument for input1, and then waits again for input2 and gives its argument?

If you can point me in the right direction it would be great; everything I found online was about multiple inputs for the actual bash script, or about multiple arguments (as a single input). I am not experienced with bash scripting as well, so I apologize in advance if my lack of experience was the reason why I couldn’t find the right resources.

Asked By: hainabaraka

||

Answers:

You can just redirect stdin to the data you want. In the shell script, you can use << to put the data in the script itself. When bash sees << EOF it pushes everything in the script up to the next "EOF" to the called program’s stdin.

test.py

#!/usr/bin/env python
input1 = input("Enter input 1")
input2 = input("Enter input 2")
print("Got", input1, input2)

test.sh

#!/bin/sh
./test.py <<EOF
I am input 1
I am input 2
EOF

This is called a Here Document and you can use any word in place of EOF.

Answered By: tdelaney
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.