我有一個帶有多個引數的 python 檔案,每個引數都是一個串列。例如,它需要一個年份串列和一個月份串列。test.py下面是:
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])
僅供參考,我曾經Convert()將引數轉換為串列。例如,引數為"2021 2020",year[1]將回傳2(而不是2021)并且year[2]將回傳0(而不是2020)而不先轉換為串列。不確定這是最準確的方法。如果你知道更好的方法,請在下面評論。
無論如何,我的主要斗爭是在命令列中,如果我運行
python test.py "2021 2020" "9 10"
它作業正常。下面是列印的訊息:
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.
但是,現在我有一個test.sh腳本可以采用相同的引數然后傳遞給 python,bash 腳本根本無法作業。test.sh腳本如下:
#!/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
然后在命令列中,我運行了這個
sh test.sh "2021 2022" "9 10"
Python 似乎相信"2021 2022" "9 10"是 4 個引數而不是 2 個引數,即使我單獨參考它們。這是它列印的訊息:
There are 1 year(s). There are 1 month(s). Working on year 2021. Working on month 2022.
我該如何解決?
uj5u.com熱心網友回復:
您應該添加雙引號以防止全球化和分詞,查看此鏈接了解更多詳細資訊:SC2086 將 test.sh 更改為:
#!/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"
uj5u.com熱心網友回復:
你可以$@用來參考所有命令列引數
# year month as arguments.
year=$1
month=$2
echo 'Working on year' $year
echo 'Working on month' $month
python path/test.py $@
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/372729.html
