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

标签 python

我试图将两个包含整数的列表作为参数传递给 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/

相关文章:

python - 如何像 Python 中的原始字符串一样处理返回/存储的字符串?

python - C+Python 和核心转储

python - 用于企业 Web 应用程序的 Django

python - 如何在Python中计算2个单词的距离

python - torch lua函数返回多个值

python - 用python过滤json文件

python - Keras 模型中的 Tensorflow 操作

python - 在Python中检测两个时间戳何时产生相同本地时间的最快方法是什么?

python - 登录 Flask 微服务内部

python - Zabbix 2.2 API 获取处理器负载(1 分钟平均值)最小/最大值 from_time,til_time