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.shscript 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?
echois not conditional, so you might be running a different script, a bogus interpreter (On a related note,shis notbash!), or something else weird.yearcontains a space-separated string which, when unquoted, expands to two distinct words after word-splitting. Your Python command waspython path/test.py 2021 2022 9 10, notpython path/test.py "2021 2022" "9 10".python test.pyI did quote the arguments. So python knows its 2 arguments. However when I runsh test.shpython seems to believe"2021 2022" "9 10"are 4 arguments instead of 2.