0

I have two files as below and I want to loop over the two files to create different combinations based on line in each file then input them as i and j to bash script in python:

file1

aaaa
tttt
cccc
gggg

file2

gggg
tttt
aaaa
cccc
ssss

I want to loop on the two files and then input them to a bash script. so every combination of i and j should be an input for bash script:

f1=[]
f2=[]
file1=open('file1.txt','r')
file2=open('file2.txt','r')

for i in file1:
    f1.append(i)

for j in file2:
    f2.append(j)

for i in f1:
    for j in f2:
        print(i)
        print(j)

bashscript i j
Apex
  • 1,055
  • 4
  • 22

1 Answers1

1

You can use subprocess.run() or subprocess.check_output() depending whether you need to simply run the script, or if you want the output to be returned in Python.

Here a silly example

bash_example.sh is

echo 'Hello from Bash'

From within python:

from subprocess import check_output

check_output('bash bash_example.sh', shell=True)
b'Hello from Bash\n'
alec_djinn
  • 10,104
  • 8
  • 46
  • 71
  • 1
    If you are explicitly running Bash anyway, `shell=True` is pretty silly (you are creating _three_ shells to execute _one_ `echo`). Probably try `check_output(['bash', 'bash_example.sh'])` though of course if the Bash script is properly executable, you can just `check_output(['bash_example.sh'])`. What's probably more interesting to the OP is how to pass Python variables as arguments to the script, but this is obviously a common duplicate. – tripleee Mar 09 '21 at 15:11
  • @tripleee You are right. I often use `shell=True` to avoid passing a list instead of a string to `check_output` and `run`. – alec_djinn Mar 09 '21 at 15:15