根据这里的反馈,我深入研究了 argparse 代码。使用子解析器的合理解决方案发布于https://stackoverflow.com/a/49977713/428542 https://stackoverflow.com/a/49977713/428542.
此外,我还找到了为每个选项添加伪操作的解决方案,以及修改格式化程序的解决方案。最后,我提出了一个混合解决方案,为每个选项添加伪操作,但通过利用一些实现细节,只有格式化程序才能使用它们。
第一个解决方案定义了一个自定义操作,其目的是不执行任何操作,但仍然打印一些使用信息。这个 NoAction 类给出了不同的选项。
import argparse
class NoAction(argparse.Action):
def __init__(self, **kwargs):
kwargs.setdefault('default', argparse.SUPPRESS)
kwargs.setdefault('nargs', 0)
super(NoAction, self).__init__(**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
pass
parser = argparse.ArgumentParser()
parser.register('action', 'none', NoAction)
parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store',
help='salutation for addressing the customer')
parser.add_argument('ingredients', nargs='*', metavar='INGREDIENT',
choices=['bacon', 'egg', 'sausage', 'spam', 'tomato'],
help='List of ingredients')
group = parser.add_argument_group(title='your choice of ingredients')
group.add_argument('bacon', help="Lovely bacon", action='none')
group.add_argument('egg', help="The runny kind", action='none')
group.add_argument('sausage', help="Just a roll", action='none')
group.add_argument('spam', help="Glorious SPAM", action='none')
group.add_argument('tomato', help="Sliced and diced", action='none')
options = parser.parse_args('--customer=Vikings egg sausage bacon'.split())
print("Dear {}, we are happy to serve you {}" \
.format(options.customer, ', '.join(options.ingredients)))
options = parser.parse_args(['--help'])
其输出:
Dear Vikings, we are happy to serve you egg, sausage, bacon
usage: customchoices.py [-h] [--customer CUSTOMER]
[INGREDIENT [INGREDIENT ...]]
positional arguments:
INGREDIENT List of ingredients
optional arguments:
-h, --help show this help message and exit
--customer CUSTOMER salutation for addressing the customer
your choice of ingredients:
bacon Lovely bacon
egg The runny kind
sausage Just a roll
spam Glorious SPAM
tomato Sliced and diced
一个小缺点是,各个选择都被添加到成分(用于解析)和解析器(用于格式化)中。我们还可以定义一个方法来直接将选项添加到成分解析器中:
import argparse
class NoAction(argparse.Action):
def __init__(self, **kwargs):
kwargs.setdefault('default', argparse.SUPPRESS)
kwargs.setdefault('nargs', 0)
super(NoAction, self).__init__(**kwargs)
def __call__(self, parser, namespace, values, option_string=None):
pass
class ChoicesAction(argparse._StoreAction):
def add_choice(self, choice, help=''):
if self.choices is None:
self.choices = []
self.choices.append(choice)
self.container.add_argument(choice, help=help, action='none')
parser = argparse.ArgumentParser()
parser.register('action', 'none', NoAction)
parser.register('action', 'store_choice', ChoicesAction)
parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store',
help='salutation for addressing the customer')
group = parser.add_argument_group(title='your choice of ingredients')
ingredients = group.add_argument('ingredients', nargs='*', metavar='INGREDIENT',
action='store_choice')
ingredients.add_choice('bacon', help="Lovely bacon")
ingredients.add_choice('egg', help="The runny kind")
ingredients.add_choice('sausage', help="Just a roll")
ingredients.add_choice('spam', help="Glorious SPAM")
ingredients.add_choice('tomato', help="Sliced and diced")
尽管有两个动作子类,上面的方法可能是我最喜欢的方法。它只使用公共方法。
另一种方法是修改格式化程序。这是可能的,它修改列表中的action.choices['option1', 'option2']
到字典{'option1': 'help_for_option1', 'option2', 'help_for_option2'}
,以及或多或少的重新实现HelpFormatter._format_action()
as HelpFormatterWithChoices.format_choices()
:
import argparse
class HelpFormatterWithChoices(argparse.HelpFormatter):
def add_argument(self, action):
if action.help is not argparse.SUPPRESS:
if isinstance(action.choices, dict):
for choice, choice_help in action.choices.items():
self._add_item(self.format_choices, [choice, choice_help])
else:
super(HelpFormatterWithChoices, self).add_argument(action)
def format_choices(self, choice, choice_help):
# determine the required width and the entry label
help_position = min(self._action_max_length + 2,
self._max_help_position)
help_width = max(self._width - help_position, 11)
action_width = help_position - self._current_indent - 2
choice_header = choice
# short choice name; start on the same line and pad two spaces
if len(choice_header) <= action_width:
tup = self._current_indent, '', action_width, choice_header
choice_header = '%*s%-*s ' % tup
indent_first = 0
# long choice name; start on the next line
else:
tup = self._current_indent, '', choice_header
choice_header = '%*s%s\n' % tup
indent_first = help_position
# collect the pieces of the choice help
parts = [choice_header]
# add lines of help text
help_lines = self._split_lines(choice_help, help_width)
parts.append('%*s%s\n' % (indent_first, '', help_lines[0]))
for line in help_lines[1:]:
parts.append('%*s%s\n' % (help_position, '', line))
# return a single string
return self._join_parts(parts)
parser = argparse.ArgumentParser(formatter_class=HelpFormatterWithChoices)
toppings = {
'bacon': "Lovely bacon",
'egg': 'The runny kind',
'sausage': 'Just a roll',
'spam': 'Glorious SPAM',
'tomato': 'Sliced and diced',
}
parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store',
help='salutation for addressing the customer')
group = parser.add_argument_group(title='your choice of ingredients')
ingredients = group.add_argument('ingredients', nargs='*', metavar='INGREDIENT',
choices=toppings)
options = parser.parse_args('--customer=Vikings egg sausage bacon'.split())
print("Dear {}, we are happy to serve you {}" \
.format(options.customer, ', '.join(options.ingredients)))
print()
options = parser.parse_args(['--help'])
其输出:
Dear Vikings, we are happy to serve you egg, sausage, bacon
usage: helpformatter.py [-h] [--customer CUSTOMER]
[INGREDIENT [INGREDIENT ...]]
optional arguments:
-h, --help show this help message and exit
--customer CUSTOMER salutation for addressing the customer
your choice of ingredients:
bacon Lovely bacon
egg The runny kind
sausage Just a roll
spam Glorious SPAM
tomato Sliced and diced
应该注意的是,这是唯一不打印“成分”本身的帮助行,而只打印选择的方法。
尽管如此,我不喜欢这种方法:它重新实现了太多代码,并且依赖于 argparse 太多的内部实现细节。
还有一种可能的混合方法:子解析器代码argparser
使用财产action._choices_actions
。这通常是在_SubParsersAction
类,用于解析和格式化。如果我们使用此属性但仅用于格式化怎么办?
import argparse
class ChoicesAction(argparse._StoreAction):
def __init__(self, **kwargs):
super(ChoicesAction, self).__init__(**kwargs)
if self.choices is None:
self.choices = []
self._choices_actions = []
def add_choice(self, choice, help=''):
self.choices.append(choice)
# self.container.add_argument(choice, help=help, action='none')
choice_action = argparse.Action(option_strings=[], dest=choice, help=help)
self._choices_actions.append(choice_action)
def _get_subactions(self):
return self._choices_actions
parser = argparse.ArgumentParser()
parser.register('action', 'store_choice', ChoicesAction)
parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store',
help='salutation for addressing the customer')
group = parser.add_argument_group(title='your choice of ingredients')
ingredients = group.add_argument('ingredients', nargs='*', metavar='INGREDIENT',
action='store_choice')
ingredients.add_choice('bacon', help="Lovely bacon")
ingredients.add_choice('egg', help="The runny kind")
ingredients.add_choice('sausage', help="Just a roll")
ingredients.add_choice('spam', help="Glorious SPAM")
ingredients.add_choice('tomato', help="Sliced and diced")
options = parser.parse_args('--customer=Vikings egg sausage bacon'.split())
print("Dear {}, we are happy to serve you {}" \
.format(options.customer, ', '.join(options.ingredients)))
print()
options = parser.parse_args(['--help'])
其输出:
Dear Vikings, we are happy to serve you egg, sausage, bacon
usage: helpformatter2.py [-h] [--customer CUSTOMER]
[INGREDIENT [INGREDIENT ...]]
optional arguments:
-h, --help show this help message and exit
--customer CUSTOMER salutation for addressing the customer
your choice of ingredients:
INGREDIENT
bacon Lovely bacon
egg The runny kind
sausage Just a roll
spam Glorious SPAM
tomato Sliced and diced
这也是一个很好的解决方案,尽管它依赖于实现细节_get_subactions()
method.