Python argparse:列出用法中的各个选项

Mac*_*eek 0 python argparse

我有一个需要多个参数的程序,例如

breakfast.py --customer=vikings eggs sausage bacon
Run Code Online (Sandbox Code Playgroud)

其中“鸡蛋”、“香肠”和“培根”可以从特定选项列表中指定。

现在我喜欢这样的输出breakfast.py --help

usage: breakfast.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...]

positional arguments:
  your choice of ingredients:
    bacon              Lovely bacon
    egg                The runny kind
    sausage            Just a roll
    spam               Glorious SPAM
    tomato             Sliced and diced

optional arguments:
  -h, --help           show this help message and exit
  --customer CUSTOMER  salutation for addressing the customer
Run Code Online (Sandbox Code Playgroud)

我尝试了两种方法,但到目前为止都失败了。

使用参数选择:

import argparse

parser = argparse.ArgumentParser()

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')
parser.add_argument('ingredients', nargs='+', choices=toppings.keys(),
                    help='your choice of ingredients')

options = parser.parse_args('--customer=Vikings egg sausage bacon'.split())
print("Dear {}, we are happy to serve you {}" \
      .format(options.customer, ', '.join(options.ingredients)))
Run Code Online (Sandbox Code Playgroud)

上面程序的用法是打印一个没有细节的字典格式的列表:

usage: breakfast.py [-h] [--customer CUSTOMER]
                      {bacon,egg,sausage,spam,tomato}
                      [{bacon,egg,sausage,spam,tomato} ...]

positional arguments:
  {bacon,egg,sausage,spam,tomato}
                        your choice of ingredients
Run Code Online (Sandbox Code Playgroud)

添加metavar='INGREDIENT'add_argument('ingredients', ...)根本不列出选项:

usage: breakfast.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...]

positional arguments:
  INGREDIENT           your choice of ingredients
Run Code Online (Sandbox Code Playgroud)

我简要地尝试使用子程序:

import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--customer', default='Mr. and Mrs. Bun', action='store',
                    help='salutation for addressing the customer')
ingredients = parser.add_subparsers(title='your choice of an ingredient',
                    dest='ingredient', metavar='ingredient')
ingredients.add_parser('bacon', help="Lovely bacon")
ingredients.add_parser('egg', help="The runny kind")
ingredients.add_parser('sausage', help="Just a roll")
ingredients.add_parser('spam', help="Glorious SPAM")
ingredients.add_parser('tomato', help="Sliced and diced")

options = parser.parse_args('--customer=Vikings spam'.split())
print("Dear {}, we are happy to serve you {}" \
      .format(options.customer, options.ingredient))
Run Code Online (Sandbox Code Playgroud)

这确实以我喜欢的方式列出了用法:

usage: breakfast.py [-h] [--customer CUSTOMER] ingredient ...

optional arguments:
  -h, --help           show this help message and exit
  --customer CUSTOMER  salutation for addressing the customer

your choice of an ingredient:
  ingredient
    bacon              Lovely bacon
    egg                The runny kind
    sausage            Just a roll
    spam               Glorious SPAM
    tomato             Sliced and diced
Run Code Online (Sandbox Code Playgroud)

默认情况下,子程序只允许选择一个选项。幸运的是,这个答案表明可以允许多个子命令),但这感觉就像一个黑客只是为了获得正确的格式。我最近从 argparse 转移到了ConfigArgParse,但这种方法在那里失败了。

我想我最好恢复使用具有多个选择的单个参数,并使用自定义格式。

不幸的是,关于调整 argparse 格式的文档很少,所以我很感激如何解决这个问题。

hpa*_*ulj 6

更改add_argument为:

parser.add_argument('ingredients', nargs='+', choices=toppings.keys(),
                metavar='INGREDIENT',
                help='your choice of ingredients: %(choices)s')
Run Code Online (Sandbox Code Playgroud)

产生

usage: stack49969605.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...]

positional arguments:
  INGREDIENT           your choice of ingredients: bacon, egg, sausage, spam,
                       tomato
Run Code Online (Sandbox Code Playgroud)

更改格式化程序:

formatter_class=argparse.RawTextHelpFormatter
Run Code Online (Sandbox Code Playgroud)

以及add_argument help参数:

                    help = """
your choice of ingredients:
bacon              Lovely bacon
egg                The runny kind
sausage            Just a roll
spam               Glorious SPAM
tomato             Sliced and diced
    """
    )
Run Code Online (Sandbox Code Playgroud)

产生:

usage: stack49969605.py [-h] [--customer CUSTOMER] INGREDIENT [INGREDIENT ...]

positional arguments:
  INGREDIENT           
                       your choice of ingredients:
                       bacon              Lovely bacon
                       egg                The runny kind
                       sausage            Just a roll
                       spam               Glorious SPAM
                       tomato             Sliced and diced
Run Code Online (Sandbox Code Playgroud)

或者您可以使用argparse.RawDescriptionHelpFormatter, 并将格式化的表放在 或descriptionepilog


另一种选择是创建一个模仿该类各个方面的 Action 子类subparsers。但这需要更深入地了解这个 Action 类在格式化中是如何处理的。

class _SubParsersAction(Action):
    class _ChoicesPseudoAction(Action):
Run Code Online (Sandbox Code Playgroud)

Action对象subparsers维护_choices_actions此类的PseudoAction列表,其目的只是为了欺骗帮助格式化程序显示子解析器,就好像它们是一组嵌套的Actions. 该列表不用于解析;仅用于帮助格式化。


Mac*_*eek 6

基于这里的反馈,我深入研究了 argparse 代码。使用子解析器的合理解决方案发布在/sf/answers/3498439941/ 上

此外,我还找到了为每个选项添加伪操作的解决方案,以及修改格式化程序的解决方案。最后,我提出了一个混合解决方案,通过利用一些实现细节,为每个选项添加伪操作,但只有格式化程序使用它们。

第一个解决方案定义了一个自定义操作,其目的是什么都不做,但仍然打印一些使用信息。这个 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'])
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

一个小缺点是单独的选择既添加到成分(用于解析)也添加到解析器(用于格式化)。我们还可以定义一个方法来直接将选项添加到成分解析器中:

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")
Run Code Online (Sandbox Code Playgroud)

以上可能是我最喜欢的方法,尽管有两个动作子类。它只使用公共方法。

另一种方法是修改格式化程序。这是可能的,它将 action.choices 从列表修改['option1', 'option2']为 dict {'option1': 'help_for_option1', 'option2', 'help_for_option2'},并且或多或少地重新实现HelpFormatter._format_action()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'])
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

应该注意的是,这是唯一不为“INGREDIENTS”本身打印帮助行而只打印选项的方法。

尽管如此,我不喜欢这种方法:它重新实现了太多代码,并且依赖于 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'])
Run Code Online (Sandbox Code Playgroud)

输出:

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
Run Code Online (Sandbox Code Playgroud)

这也是一个不错的解决方案,尽管它依赖于方法的实现细节_get_subactions()