【发布时间】:2021-10-18 15:12:18
【问题描述】:
我正在使用 argparse 指定一些参数,如下所示:
my_parser = argparse.ArgumentParser()
my_parser.add_argument("--script_path", nargs='?', type=str, const='', default='', help="Path of the script to pull.")
my_parser.add_argument("--script", nargs='?', type=str, const='', default='', help="Name of the script to get pulled, without script extension.")
my_parser.add_argument("--project", nargs='?', type=str, const='', default='', help="Project.")
my_args = my_parser.parse_args()
my_script_path = my_args.script_path
my_script = my_args.script
my_project = my_args.project
现在我正在尝试做同样的事情,而是通过我将加载的 .json 文件定义上述参数。我选择 .json 是因为它看起来不错,请随时提出更好的建议。
我尝试过的是有一个这样的 .json 文件:
[
{
"name_or_flags": ["-sp", "--script_path"],
"nargs": "?",
"const": "",
"default": "",
"type": "str",
"help": "The absolute path of the script to run."
},
...
]
加载文件后,我在下面尝试并失败了:
my_parser.add_argument(<combination of all keys, values from .json as a dictionary>)
my_parser.add_argument(<*unnamed_tup, **named_dict>)
#unnamed tuple since name_or_flags isn't supposed to be used
#unnamed tuple is only made from name_or_flags
不管我做什么都行不通。
有没有人做过类似的事情?
我不希望通过外部文件添加值,例如:Using Argparse and Json together
只是为了定义参数。
谢谢!
【问题讨论】:
-
由于您只为您的 add_argument 代码提供了伪代码,因此您需要指定您收到的错误消息,可能会出现很多错误
标签: python json python-3.x argparse