I am having a python file that take multiple arguments, each argument is a list. For example, it takes a list of year and a list of month.The test.py
is below:
import sys
def Convert(string):
li = list(string.split(" "))
return li
year= Convert(sys.argv[1])
month = Convert(sys.argv[2])
print("There are",len(year),"year(s)")
print("There are",len(month),"month(s)")
for i in range(len(year)):
print("Working on year",year[i])
for j in range(len(month)):
print("Working on month",month[j])
Just FYI, I used Convert()
to convert arguments into lists. For example, with an argument of "2021 2020"
,year[1]
will return 2
(instead of 2021
) and year[2]
will return 0
(instead of 2020
) without being converting into a list first. Not sure this is the most accurate way to do it though.If you know a better way, please comment down below.
Anyway, my main struggle is that in command line, if I run
python test.py "2021 2020" "9 10"
It worked fine.And below is the printed message:
There are 2 year(s). There are 2 month(s). Working on year 2021. Working on month 9. Working on month 10. Working on year 2022. Working on month 9. Working on month 10.
However, now I have a test.sh
script that can take the same arguments then pass into python, the bash script just simply won't work.The test.sh
script is below:
#!/bin/bash
# year month as arguments.
year=$1
month=$2
echo 'Working on year' $year
echo 'Working on month' $month
python path/test.py $year $month
Then in command line, I ran this
sh test.sh "2021 2022" "9 10"
Python seems to believe "2021 2022" "9 10"
is 4 arguments instead of 2 even though I quote them separately.
Here is the message it prints:
There are 1 year(s). There are 1 month(s). Working on year 2021. Working on month 2022.
How do I fix this?
CodePudding user response:
You should add double quote to prevent globing and word splitting, check this link for more details: SC2086 Change test.sh to:
#!/bin/bash
# year month as arguments.
year=$1
month=$2
echo 'Working on year' "$year"
echo 'Working on month' "$month"
python path_to_test.py/test.py "$year" "$month"
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
you could use $@
to refer to all command-line arguments
# year month as arguments.
year=$1
month=$2
echo 'Working on year' $year
echo 'Working on month' $month
python path/test.py $@