Home > database >  Run Python app once & give it input from a text file line-by-line in Bash
Run Python app once & give it input from a text file line-by-line in Bash

Time:07-16

I have a simple Python app that takes two inputs in separate lines and prints a result...

def f(n, x):
    if n == 0:
        return 0
    # print string n times
    print(n*x)

# number
n = int(input())
# string
x = input()
print(f(n, x))

Want to give inputs to the Python app from a .txt file and store the compiled outputs in another file (output.txt), the inputs.txt file contains these inputs:

3
a
4
b
5
c
⋮
0

The app should run once and then take each line as input...
How can I do that in Bash?
The output.txt should be like this:

aaa
bbbb
ccccc

P.S
I tried the below script but that was a disaster as the Python app runs again and only takes the first input!

while IFS= read -r line || [[ -n "$line" ]]; do
    python3 main.py | "$line"
done < inputs.txt >> output.txt

CodePudding user response:

Your Python script already iterates over its input line-by-line. You don't need to do much of anything in bash except provide the file to Python.

python3 main.py < inputs.txt > output.txt

CodePudding user response:

If you want to feed the values from Bash to Python, your python script needs to receive both the number and the character. Have you tried reading lines 2 by 2 in your Bash loop?

Like

while read -r nbChar; read -r theChar [...]
  • Related