使用 Python 的 argparser 模块基于参数组的扩展帮助

问题描述 投票:0回答:1

考虑以下玩具示例:

cat extended_help.py
import argparse

ap = argparse.ArgumentParser()
ap.add_argument("-H", "--help-all", action = "version",
                help = """show extended help message (incl. advanced
                       parameters) and exit""",
                version = "This is just a dummy implementation.")
common_args = ap.add_argument_group("common parameters",
                                    """These parameters are typically
                                    enough to run the tool. `%(prog)s
                                    -h|--help` should list these
                                    parameters.""")
advanced_args = ap.add_argument_group("advanced parameters",
                                      """These parameters are for advanced
                                      users with special needs only. To make
                                      the help more accessible, `%(prog)s
                                      -h|--help` should not include these
                                      parameters, while `%(prog)s
                                      -H|--help-all` should include them (in
                                      addition to those included by `%(prog)s
                                      -h|--help`.""")
common_args.add_argument("-f", "--foo", metavar = "<foo>",
                         help = "the very common Foo parameter")
common_args.add_argument("--flag", action = "store_true",
                         help = "a flag enabling a totally normal option")
advanced_args.add_argument("-b", "--bar", metavar = "<bar>",
                           help = "the rarely needed Bar parameter")
advanced_args.add_argument("-B", "--baz", metavar = "<bar>",
                           help = "the even more obscure Baz parameter")
advanced_args.add_argument("--FLAG", action = "store_true",
                           help = "a flag for highly advanced users only")
ap.parse_args()
python extended_help.py -h

打印

usage: extended_help.py [-h] [-H] [-f <foo>] [--flag] [-b <bar>] [-B <bar>] [--FLAG]

options:
  -h, --help       show this help message and exit
  -H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
  These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

  -f, --foo <foo>  the very common Foo parameter
  --flag           a flag enabling a totally normal option

advanced parameters:
  These parameters are for advanced users with special needs only. To make the help more accessible, `extended_help.py -h|--help` should not include these parameters, while
  `extended_help.py -H|--help-all` should include them (in addition to those included by `extended_help.py -h|--help`.

  -b, --bar <bar>  the rarely needed Bar parameter
  -B, --baz <bar>  the even more obscure Baz parameter
  --FLAG           a flag for highly advanced users only

同时

python extended_help.py -H

仅生成占位符消息

This is just a dummy implementation.

我需要如何修改

extended_help.py
才能拥有

python extended_help.py -h

仅限打印

usage: extended_help.py [-h] [-H] [-f <foo>] [--flag] [-b <bar>] [-B <bar>] [--FLAG]

options:
  -h, --help       show this help message and exit
  -H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
  These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

  -f, --foo <foo>  the very common Foo parameter
  --flag           a flag enabling a totally normal option

并且有

python extended_help.py -H

重现当前打印的完整帮助消息

python extended_help.py -h

我正在寻找一种解决方案,避免手动复制帮助消息(某些参数)。


编辑

我知道我可以用

-H
替换
-h
,如下所示:

import argparse

ap = argparse.ArgumentParser(add_help = False)
ap.add_argument("-h", "--help", action = "version",
                help = "show help message (common parameters only) and exit",
                version = """I know I could add the entire (short) help here
                          but I'd like to avoid that.""")
ap.add_argument("-H", "--help-all", action = "help",
                help = """show extended help message (incl. advanced
                       parameters) and exit""")
common_args = ap.add_argument_group("common parameters",
                                    """These parameters are typically
                                    enough to run the tool. `%(prog)s
                                    -h|--help` should list these
                                    parameters.""")
# The rest would be the same as above.

这边,

python extended_help.py -H

已经按预期工作:

usage: extended_help.py [-h] [-H] [-f <foo>] [--flag] [-b <bar>] [-B <bar>] [--FLAG]

options:
  -h, --help       show help message (common parameters only) and exit
  -H, --help-all   show extended help message (incl. advanced parameters) and exit

common parameters:
  These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

  -f, --foo <foo>  the very common Foo parameter
  --flag           a flag enabling a totally normal option

advanced parameters:
  These parameters are for advanced users with special needs only. To make the help more accessible, `extended_help.py -h|--help` should not include these parameters, while
  `extended_help.py -H|--help-all` should include them (in addition to those included by `extended_help.py -h|--help`.

  -b, --bar <bar>  the rarely needed Bar parameter
  -B, --baz <bar>  the even more obscure Baz parameter
  --FLAG           a flag for highly advanced users only

但是,现在

python extended_help.py -h

仅打印占位符:

I know I could add the entire help here but I'd like to avoid that.

我设法非常接近:

import argparse

ap = argparse.ArgumentParser(add_help = False, conflict_handler = "resolve")
ap.add_argument("-h", "--help", action = "help",
                help = "show help message (common parameters only) and exit")
ap.add_argument("-H", "--help-all", action = "help",
                help = """show extended help message (incl. advanced
                       parameters) and exit""")
common_args = ap.add_argument_group("common parameters",
                                    """These parameters are typically
                                    enough to run the tool. `%(prog)s
                                    -h|--help` should list these
                                    parameters.""")
common_args.add_argument("-f", "--foo", metavar = "<foo>",
                         help = "the very common Foo parameter")
common_args.add_argument("--flag", action = "store_true",
                         help = "a flag enabling a totally normal option")
ap.add_argument("-h", "--help", action = "version", version = ap.format_help())
advanced_args = ap.add_argument_group("advanced parameters",
                                      """These parameters are for advanced
                                      users with special needs only. To make
                                      the help more accessible, `%(prog)s
                                      -h|--help` should not include these
                                      parameters, while `%(prog)s
                                      -H|--help-all` should include them (in
                                      addition to those included by `%(prog)s
                                      -h|--help`.""")
advanced_args.add_argument("-b", "--bar", metavar = "<bar>",
                           help = "the rarely needed Bar parameter")
advanced_args.add_argument("-B", "--baz", metavar = "<bar>",
                           help = "the even more obscure Baz parameter")
advanced_args.add_argument("--FLAG", action = "store_true",
                           help = "a flag for highly advanced users only")
ap.parse_args()

这会在添加高级参数之前捕获帮助消息,并覆盖用于存储/打印简短帮助的

-h|--help
标志的“版本”字符串 (ab-)。

python extended_help.py -H

已经按预期工作,但是

python extended_help.py -h

吞掉帮助消息中的所有换行符和空格:

usage: extended_help.py [-h] [-H] [-f <foo>] [--flag] options: -h, --help show help message (common parameters only) and exit -H, --help-all show extended help message (incl.
advanced parameters) and exit common parameters: These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters. -f, --foo
<foo> the very common Foo parameter --flag a flag enabling a totally normal option
python command-line command-line-interface command-line-arguments argparse
1个回答
0
投票

这是我想出的解决方案:

import argparse

# See https://stackoverflow.com/a/8632404/2451238 + argparse._HelpAction source
def short_help(help_message):
  class shortHelpAction(argparse.Action):
    def __init__(self,
                 option_strings,
                 dest = argparse.SUPPRESS,
                 default = argparse.SUPPRESS,
                 help = None,
                 deprecated = False):
      super(shortHelpAction, self).__init__(
            option_strings = option_strings,
            dest = dest,
            default = default,
            nargs = 0,
            help = help,
            deprecated = deprecated)
    def __call__(self, parser, namespace, args, option_string = None):
        print(help_message)
        parser.exit()
  return shortHelpAction

ap = argparse.ArgumentParser(add_help = False, conflict_handler = "resolve")
ap.add_argument("-h", "--help", action = short_help(None),
                help = "show help message (common parameters only) and exit")
ap.add_argument("-H", "--help-all", action = "help",
                help = """show extended help message (incl. advanced
                       parameters) and exit""")
ap.add_argument("-v", "--version", action = "version", version = "1.0")
common_args = ap.add_argument_group("common parameters",
                                    """These parameters are typically
                                    enough to run the tool. `%(prog)s
                                    -h|--help` should list these
                                    parameters.""")
common_args.add_argument("-f", "--foo", metavar = "<foo>",
                         help = "the very common Foo parameter")
common_args.add_argument("--flag", action = "store_true",
                         help = "a flag enabling a totally normal option")
ap.add_argument("-h", "--help", action = short_help(ap.format_help()))
advanced_args = ap.add_argument_group("advanced parameters",
                                      """These parameters are for advanced
                                      users with special needs only. To make
                                      the help more accessible, `%(prog)s
                                      -h|--help` should not include these
                                      parameters, while `%(prog)s
                                      -H|--help-all` should include them (in
                                      addition to those included by `%(prog)s
                                      -h|--help`.""")
advanced_args.add_argument("-b", "--bar", metavar = "<bar>",
                           help = "the rarely needed Bar parameter")
advanced_args.add_argument("-B", "--baz", metavar = "<bar>",
                           help = "the even more obscure Baz parameter")
advanced_args.add_argument("--FLAG", action = "store_true",
                           help = "a flag for highly advanced users only")
ap.parse_args()
python extended_help.py -h

打印

usage: extended_help.py [-h] [-H] [-v] [-f <foo>] [--flag]

options:
  -h, --help       show help message (common parameters only) and exit
  -H, --help-all   show extended help message (incl. advanced parameters) and exit
  -v, --version    show program's version number and exit

common parameters:
  These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

  -f, --foo <foo>  the very common Foo parameter
  --flag           a flag enabling a totally normal option

,

python extended_help.py -v
1.0

,和

python extended_help.py -H

usage: extended_help.py [-H] [-v] [-f <foo>] [--flag] [-h] [-b <bar>] [-B <bar>] [--FLAG]

options:
  -H, --help-all   show extended help message (incl. advanced parameters) and exit
  -v, --version    show program's version number and exit
  -h, --help

common parameters:
  These parameters are typically enough to run the tool. `extended_help.py -h|--help` should list these parameters.

  -f, --foo <foo>  the very common Foo parameter
  --flag           a flag enabling a totally normal option

advanced parameters:
  These parameters are for advanced users with special needs only. To make the help more accessible, `extended_help.py -h|--help` should not include these parameters, while
  `extended_help.py -H|--help-all` should include them (in addition to those included by `extended_help.py -h|--help`.

  -b, --bar <bar>  the rarely needed Bar parameter
  -B, --baz <bar>  the even more obscure Baz parameter
  --FLAG           a flag for highly advanced users only

.

© www.soinside.com 2019 - 2024. All rights reserved.