我正在尝试创建一段Bash脚本,该脚本将自己的参数传递给Python脚本。 我希望它能像这样工作。
如果我像这样运行它:
script.sh latest
然后在 Bash 脚本中,它会使用 "latest" 参数运行 Python 脚本,就像这样:
python script.py latest
同样,如果使用参数123运行bash脚本,则Python脚本如下所示:python script.py 123
有人能帮我理解如何完成这个吗?
我正在尝试创建一段Bash脚本,该脚本将自己的参数传递给Python脚本。 我希望它能像这样工作。
如果我像这样运行它:
script.sh latest
然后在 Bash 脚本中,它会使用 "latest" 参数运行 Python 脚本,就像这样:
python script.py latest
同样,如果使用参数123运行bash脚本,则Python脚本如下所示:python script.py 123
有人能帮我理解如何完成这个吗?
在这种情况下,关键是传递您拥有的所有参数,包括没有参数的情况,并保留原始命令行中存在的任何分组。
因此,您希望使这三种情况起作用:
script.sh # no args
script.sh how now # some number
script.sh "how now" "brown cow" # args that need to stay quoted
其实并没有一种自然的方式来做到这一点,因为shell是一种宏语言,所以他们添加了一些神奇的语法,这些语法会自动处理。
#!/bin/sh
python script.py "$@"
script.py
中,使用getopt.getopt(args, options[, long_options])
获取参数。import getopt, sys
def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "ho:v", ["help", "output="])
except getopt.GetoptError as err:
# print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
output = None
verbose = False
for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-o", "--output"):
output = a
else:
assert False, "unhandled option"
# ...
if __name__ == "__main__":
main()
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
$#
符号(#是一个数字)来访问传递给脚本的参数。使用$#就可以得到传递的参数数量。因此,如果您想要传递参数:
调用脚本:
`#script.sh argument`
在脚本内部:
python script.py "$1"
"$1"
以保留空格。 - glenn jackman