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 
1
  • Use os.system() or subprocess.call() to execute Commented Mar 9, 2021 at 15:05

1 Answer 1

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' 
Sign up to request clarification or add additional context in comments.

2 Comments

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 You are right. I often use shell=True to avoid passing a list instead of a string to check_output and run.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.