我试图将两个包含整数的列表作为参数传递给 python 代码。但是 sys.argv[i] 获取参数作为字符串列表。
输入看起来像,
$ python filename.py [2,3,4,5] [1,2,3,4]
我发现了以下技巧来转换列表。
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/54171956/