【问题标题】:Pass multiple arguments (each argument is a list) from bash script to python script将多个参数(每个参数是一个列表)从 bash 脚本传递到 python 脚本
【发布时间】: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 不是有条件的,因此您可能正在运行不同的脚本、伪造的解释器(在相关说明中,sh is not bash!)或其他奇怪的东西。
  • 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 你是对的。我编辑了我的问题。

标签: python bash arguments


【解决方案1】:

您应该添加双引号以防止全局和分词,请查看此链接了解更多详细信息: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"

【讨论】:

  • 我试过了。然后消息变成Working on $year而不是2021什么的
  • @tuangou 分享结果
  • @tuangou 你用的是'$year'还是"$year"
【解决方案2】:

您可以使用$@ 来引用所有命令行参数


# year month as arguments.
year=$1
month=$2

echo 'Working on year' $year 
echo 'Working on month' $month

python path/test.py $@

【讨论】:

  • 我试过了。这没有改变。
猜你喜欢
  • 2021-11-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 2013-03-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多