我试图将两个包含整数的列表作为参数传递给 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模块 https://docs.python.org/3/library/argparse.html,明确并传递实际的参数列表
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]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)