Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
198 views
in Technique[技术] by (71.8m points)

python - Passing string argument from bash script to python3

I am trying to read multiple directory locations from a text file using a bash script and pass as argument to another python script. The directory name contains space which shows

test.py: error: unrecognized arguments: 1B/PHASE/PHASE_90

I am using following bash script:

filename='filter_directory.txt'
line_counter=1
while read line; do
# reading each line
    echo "Processing Directorie: $line_counter : $line"
    python3 test.py -i $line
    line_counter=$((line_counter+1))
    echo "Finish Directorie: $line_counter!!!"
    done < $filename

test.py is:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--input", "-i", type=str, default='./input', help='Calculation LUMA image folder')
arg = parser.parse_args()
input_path = arg.input
print(input_path)

filter_directory.txt contains:

version_of_study/Study 1B/PHASE/PHASE_90
version_of_study/Study 1B/PHASE/PHASE_91
version_of_study/Study 1B/PHASE/PHASE_92
version_of_study/Study 1B/PHASE/PHASE_93

Could you help me to import the directory name from text file to python by bash script?

question from:https://stackoverflow.com/questions/66055368/passing-string-argument-from-bash-script-to-python3

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should just quote $line like python3 test.py -i "$line" to group the argument. You can use tools like shellcheck to identify issues like these in shell scripts. This article is a great introduction to the different ways to correct use/avoid variable expansion and word splitting.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...