gpt4 book ai didi

python - 如何在 Python 中将整个列表作为命令行参数传递?

转载 作者:IT老高 更新时间:2023-10-28 21:05:32 27 4
gpt4 key购买 nike

我试图将两个包含整数的列表作为参数传递给 python 代码。但是 sys.argv[i] 将参数作为字符串列表获取。

输入看起来像,

$ python filename.py [2,3,4,5] [1,2,3,4]

我发现了以下 hack 来转换列表。

strA = sys.argv[1].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
strB = sys.argv[2].replace('[', ' ').replace(']', ' ').replace(',', ' ').split()
A = [float(i) for i in strA]
B = [float (i) for i in strB]

有没有更好的方法来做到这一点?

最佳答案

不要重新发明轮子。使用 argparse module , 明确并传入实际的参数列表

import argparse
# defined command line options
# this also generates --help and error handling
CLI=argparse.ArgumentParser()
CLI.add_argument(
"--lista", # name on the CLI - drop the `--` for positional/required parameters
nargs="*", # 0 or more values expected => creates a list
type=int,
default=[1, 2, 3], # default if nothing is provided
)
CLI.add_argument(
"--listb",
nargs="*",
type=float, # any type/callable can be used here
default=[],
)

# parse the command line
args = CLI.parse_args()
# access CLI options
print("lista: %r" % args.lista)
print("listb: %r" % args.listb)

然后您可以使用它调用它

$ python my_app.py --listb 5 6 7 8 --lista  1 2 3 4
lista: [1, 2, 3, 4]
listb: [5.0, 6.0, 7.0, 8.0]

关于python - 如何在 Python 中将整个列表作为命令行参数传递?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32761999/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com