Chrys
Chrys

Reputation: 313

Using ls to launch a Python script on each subdirectory

I created this little Python script Essai_Bash.py to make some tests:

#!/usr/bin/python

import argparse
import os

parser = argparse.ArgumentParser()
parser.add_argument('-i', action='store', dest='InputDir', help='Working Directory') # Empty folders for outputs.

parser.add_argument('--version', action='version', version='%(prog)s 0.1')

results = parser.parse_args()
print 'Current input directory      =', results.InputDir

dir_path=str(os.path.abspath(results.InputDir)) # Retrieving an output folder name to use as species ID:
path,CodeSp = os.path.split(dir_path)

print "Currently working on species:      "+str(CodeSp)

Back to my shell, I type the following command, expecting my script to run on each directory that is present in my "Essai_Bash" folder:

listdir='ls ../Main_folder/' # I first used backtips instead of simple quotes but it did not work.
for dir in $listdir; do ./Essai_Bash.py -i ../Main_folder/$dir; done

I am surely missing something obvious but it does not work. It seems like $listdir is considered as a characters strings and not a list of directories. However, just typing $listdir in my shell actually gives me this list!

Upvotes: 1

Views: 43

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

Just use glob extension, parsing ls output is not safe. Also dir variable already contains ../Main_folder/

listdir=( ../Main_folder/*/ )
for dir in "${listdir[@]}"; do ./Essai_Bash.py -i "$dir"; done

Upvotes: 2

Related Questions