【发布时间】:2022-01-07 13:31:49
【问题描述】:
我有一个带有多个参数的 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.
我该如何解决这个问题?
【问题讨论】:
-
“什么都没发生”是什么意思?它甚至不打印“Working on year”吗?
-
听起来完全不同的事情正在发生。
echo不是有条件的,因此您可能正在运行不同的脚本、伪造的解释器(在相关说明中,shis notbash!)或其他奇怪的东西。 -
year包含一个以空格分隔的字符串,当 不加引号 时,它会在分词后扩展为两个不同的词。你的 Python 命令是python path/test.py 2021 2022 9 10,而不是python path/test.py "2021 2022" "9 10"。 -
@chepner 抱歉,我不确定我是否关注了。当我运行
python test.py时,我确实引用了这些论点。所以 python 知道它的 2 个参数。但是,当我运行sh test.sh时,python 似乎相信"2021 2022" "9 10"是 4 个参数而不是 2 个。 -
@l0b0 你是对的。我编辑了我的问题。