使用字典类型变量向参数解析器 python 添加参数

发布于 2025-01-14 14:58:51 字数 1726 浏览 1 评论 0原文

我有一个 CLI 参数解析器,我正在尝试构建使用包含这些详细信息的预定义字典动态添加参数规范的部分。 这是包含详细信息的字典:

paramsDetails = {
'inputpath': {
    '-': 'i',
    '--': '--inputpath',
    'dest': 'userinputpath',
   'type': 'str',
   'metavar': 'PATH',
   'help': 'REQUIRED, input path of base folder of the files in which to scan. ',
   'required': True
},

'depth': {
    '-': 'd',
    '--': '--depth',
    'dest': 'directorydepth',
   'type': 'int',
   'metavar': 'INT',
   'help': 'depth to do down in path. ',
}

}

“paramsDetails”字典详细信息是从我无法控制的外部源检索的,并且它可能随时在我不知情的情况下发生更改 所以我不能在我的代码中手动对其进行硬编码。 我需要能够在不知道“paramsDetails”内容的情况下动态构建“parser.add_argument”调用。 我不一定需要“parser.add_argument”来购买,需要使用“paramsDetails”字典。

这就是我到目前为止得到的:

from argparse import ArgumentParser

parser = ArgumentParser(description='My test')

for currentParamDetails in paramsDetails:
    parser.add_argument(currentParamDetails)

args = parser.parse_args()

“parser.add_argument(currentParamDetails)”不起作用。 我明白了:

usage: tests.py [-h] -i PATH [-d INT] inputpath depth
tests.py: error: the following arguments are required: inputpath, depth

这意味着一切都出了问题。

当然,手动输入参数是这样的:

from argparse import ArgumentParser

parser = ArgumentParser(description='My test')

parser.add_argument("-i", "--inputpath", dest="userinputpath", type=str, metavar="PATH", help="REQUIRED, input path of base folder of the files in which to scan. ", required=True)

parser.add_argument("-d", "--depth", dest="directorydepth", type=int, metavar="INT", default=2, help="depth to do down in path. ")

args = parser.parse_args()

但这不是我想要的,我想使用字典。

这怎么能做到呢?

我使用的Python版本是3.6。

I have a CLI argument parser and I'm trying to build the parts that adds the specifications of the arguments dynamically with a pre defined dictionary that contains those details.
This is dictionary with the details:

paramsDetails = {
'inputpath': {
    '-': 'i',
    '--': '--inputpath',
    'dest': 'userinputpath',
   'type': 'str',
   'metavar': 'PATH',
   'help': 'REQUIRED, input path of base folder of the files in which to scan. ',
   'required': True
},

'depth': {
    '-': 'd',
    '--': '--depth',
    'dest': 'directorydepth',
   'type': 'int',
   'metavar': 'INT',
   'help': 'depth to do down in path. ',
}

}

The "paramsDetails" dictionary details are retrieved from a external source out of my control and it might change without my knowledge at any time
so I can't be manually hard coding it in my code.
I need to be able to build the "parser.add_argument" call dynamically without knowing the content of "paramsDetails".
I don't necessarily need to "parser.add_argument" for this buy DO need to use the "paramsDetails" dict.

This is what I got so far:

from argparse import ArgumentParser

parser = ArgumentParser(description='My test')

for currentParamDetails in paramsDetails:
    parser.add_argument(currentParamDetails)

args = parser.parse_args()

the "parser.add_argument(currentParamDetails)" doesn't work.
I get:

usage: tests.py [-h] -i PATH [-d INT] inputpath depth
tests.py: error: the following arguments are required: inputpath, depth

which means it all went wrong.

of course typing the arguments manually works as so:

from argparse import ArgumentParser

parser = ArgumentParser(description='My test')

parser.add_argument("-i", "--inputpath", dest="userinputpath", type=str, metavar="PATH", help="REQUIRED, input path of base folder of the files in which to scan. ", required=True)

parser.add_argument("-d", "--depth", dest="directorydepth", type=int, metavar="INT", default=2, help="depth to do down in path. ")

args = parser.parse_args()

but that's not what I want, I want to use the dict.

How can this be done?

The Python version I'm using is 3.6.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晨曦÷微暖 2025-01-21 14:58:51

这是你可以做的事情。短标志上缺少“-”对我来说似乎有点奇怪,但这不是什么大问题。将“类型”作为字符串而不是对象会产生更多问题,但假设它们始终是内置类型(如您的示例中所示),这应该可以工作:

parser = ArgumentParser(description='My test')

for definition in paramsDetails.values():
    flags = []
    flag_short = definition.pop("-", None)
    if flag_short:
        flags.append(f"-{flag_short}")
    flag_long = definition.pop("--", None)
    if flag_long:
        flags.append(flag_long)
    if "type" in definition:
        definition["type"] = getattr(__builtins__, definition["type"])
    parser.add_argument(*flags, **definition)
args = parser.parse_args(["-h"])

Here's something you can do. Missing the "-" on the short flag seems kinda strange to me but it is not a big deal. Having the "type" as a string instead of an object is more problematic, but assuming they are always builtin types (like in your examples) this should work:

parser = ArgumentParser(description='My test')

for definition in paramsDetails.values():
    flags = []
    flag_short = definition.pop("-", None)
    if flag_short:
        flags.append(f"-{flag_short}")
    flag_long = definition.pop("--", None)
    if flag_long:
        flags.append(flag_long)
    if "type" in definition:
        definition["type"] = getattr(__builtins__, definition["type"])
    parser.add_argument(*flags, **definition)
args = parser.parse_args(["-h"])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文