【问题标题】:Choices are shown for each flags in argParser python在 argParse python 中为每个标志显示选项
【发布时间】:2020-04-15 00:16:18
【问题描述】:
argParser.add_argument(
            "--operation",
            "-o",
            action="store",
            required=True,
            choices=["VIEW","ADD","EDIT","DELETE"],
            type=str.upper
        )

实际输出:

root$ myArg -h
required arguments:
  --operation {VIEW,ADD,EDIT,DELETE,INFO}, -o {VIEW,ADD,EDIT,DELETE,INFO}

所需输出:

root$ myArg -h
required arguments:
  --operation/-o {VIEW,ADD,EDIT,DELETE,INFO}

提前致谢

【问题讨论】:

标签: python argparse


【解决方案1】:

您的问题的简短回答是:您的要求与模块的功能相反。

考虑 argparse.py:652(版本 1.1;Anaconda3,python 3.7.6)

    # if the Optional takes a value, format is:
    #    -s ARGS, --long ARGS
    else:
        default = self._get_default_metavar_for_optional(action)
        args_string = self._format_args(action, default)
        for option_string in action.option_strings:
            parts.append('%s %s' % (option_string, args_string))

您看到的是明确预期的行为。

我没有看到任何明显的参数会改变这种行为。我看到的唯一选项(诚然,看了 3 分钟之后)是创建一个自定义格式化程序,该格式化程序与默认格式化程序完全相同,并覆盖了违规方法 (_format_action_invocation),以便您可以做一些与交付行为不同的事情。

这里有一个例子,它至少具有做你想做的事情的特点。我从 argparse.py 复制了代码并更改了有问题的代码以执行您喜欢的操作。

import argparse

class CustomFormatter(argparse.HelpFormatter):
    def _format_action_invocation(self, action):
        if action.option_strings and action.nargs != 0:
            # This is the code path that we don't like.
            default = self._get_default_metavar_for_optional(action)
            args_string = self._format_args(action, default)
            return '%s %s' % ('/'.join(action.option_strings), args_string)

        # For everything else, use the default behavior.
        return super()._format_action_invocation(action)

argParser = argparse.ArgumentParser( formatter_class = CustomFormatter )
argParser.add_argument(
            "--operation",
            "-o",
            action="store",
            required=True,
            choices=["VIEW","ADD","EDIT","DELETE"],
            type=str.upper
        )

argParser.parse_args()

这是输出:

# python soln.py --help
usage: soln.py [-h] --operation {VIEW,ADD,EDIT,DELETE}

optional arguments:
  -h, --help            show this help message and exit
  --operation/-o {VIEW,ADD,EDIT,DELETE}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2017-08-25
  • 2012-07-15
  • 2017-07-12
  • 2018-04-03
  • 2017-08-30
  • 2016-04-16
  • 2013-08-31
  • 2014-09-15
相关资源
最近更新 更多