从ArgumentParser获取允许的参数的正确方法 [英] Correct way to get allowed arguments from ArgumentParser
问题描述
问题:从现有的argparse.ArgumentParser
对象访问可能的参数的预期/正式方式是什么?
Question: What is the intended / official way of accessing possible arguments from an existing argparse.ArgumentParser
object?
示例:让我们假设以下上下文:
Example: Let's assume the following context:
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--foo', '-f', type=str)
在这里,我想获得以下允许的参数列表:
Here I'd like to get the following list of allowed arguments:
['-h', '--foo', '--help', '-f']
我发现以下变通办法可以帮我解决问题
I found the following workaround which does the trick for me
parser._option_string_actions.keys()
但是我对此不满意,因为它涉及访问未正式记录的_
成员.什么是此任务的正确替代方法?
But I'm not happy with it, as it involves accessing a _
-member that is not officially documented. Whats the correct alternative for this task?
推荐答案
我认为没有一种更好"的方式来实现您想要的目标.
I don't think there is a "better" way to achieve what you want.
如果您真的不想使用_option_string_actions
属性,则可以处理parser.format_usage()
来检索选项,但是这样做,您只会得到简短的选项名称.
If you really don't want to use the _option_string_actions
attribute, you could process the parser.format_usage()
to retrieve the options, but doing this, you will get only the short options names.
如果同时需要短名称和长名称,则可以处理parser.format_help()
.
If you want both short and long options names, you could process the parser.format_help()
instead.
可以使用非常简单的正则表达式来完成此过程:-+\w+
This process can be done with a very simple regular expression: -+\w+
import re
OPTION_RE = re.compile(r"-+\w+")
PARSER_HELP = """usage: test_args_2.py [-h] [--foo FOO] [--bar BAR]
optional arguments:
-h, --help show this help message and exit
--foo FOO, -f FOO a random options
--bar BAR, -b BAR a more random option
"""
options = set(OPTION_RE.findall(PARSER_HELP))
print(options)
# set(['-f', '-b', '--bar', '-h', '--help', '--foo'])
或者您可以首先制作一个包含参数解析器配置的字典,然后从中构建argmuent解析器.这样的词典可以将选项名称作为键,将选项配置作为值.这样做,您可以通过使用
如果我不愿意使用 This last way is what I would do, if I was reluctant to use 这篇关于从ArgumentParser获取允许的参数的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!_option_string_actions
,这是我会做的最后一件事._option_string_actions
.