Python argparse:有没有办法只打印特定参数的帮助?

发布于 2025-01-09 05:15:03 字数 254 浏览 2 评论 0原文

我有一个很长的参数列表,因此 mycommand --help 的输出变得非常大。我想为我的用户提供一种仅获取特定参数的帮助文本的方法。

像这样的东西(不起作用,显示整个帮助文本)

mycommand --help --parameter-of-interest

我不想将所有内容拆分为子解析器(如果可以避免的话)。

I have a long list of parameters, so the output from mycommand --help is getting very big. I would like to provide my users a way to get the help text for only a specific parameter.

Something like this (doesn't work, shows the whole help text)

mycommand --help --parameter-of-interest

I don't want to split everything into subparsers if at all avoidable.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

○愚か者の日 2025-01-16 05:15:03

您可以创建自己的操作来实现这一目标。这两个都将迭代可选参数并抑制 sys.argv 中未找到的任何参数。我建议使用解释操作,因为这不会与 -h/--help 标志混淆。

解释操作

这将创建一个带有相应-e/--explain选项的操作ExplainParamsAction,该选项可过滤仅指定参数的帮助文本。

import sys
import argparse

class ExplainParamsAction(argparse.Action):
    def __init__(
        self,
        option_strings,
        dest=argparse.SUPPRESS,
        default=argparse.SUPPRESS,
        **kwargs
    ):
        super().__init__(option_strings, dest, default=default, nargs=0, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        opts = parser._option_string_actions
        for arg in opts:
            if arg not in sys.argv:
                setattr(opts[arg], "help", argparse.SUPPRESS)
        parser.print_help()
        parser.exit()

parser = argparse.ArgumentParser()
parser.add_argument(
    "-e",
    "--explain",
    action=ExplainParamsAction,
    help="Show help message for only specified parameters and exit",
)
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

覆盖帮助操作

或者,您可以覆盖提供给解析器的帮助操作。
argparse.ArgumentParser 你需要关闭默认的助手并提供你自己的。

import sys
import argparse

class _CustomHelpAction(argparse._HelpAction):
    def __call__(self, parser, namespace, values, option_string=None):
        args = sys.argv[1:]
        opts = parser._option_string_actions
        # Check is needed for just -h/--help to work
        if len(args) > 1:
            for arg in opts:
                if arg not in args:
                    setattr(opts[arg], "help", argparse.SUPPRESS)
        super().__call__(parser, namespace, values, option_string)


# Init parser with help turned off
parser = argparse.ArgumentParser(add_help=False)

# Register your help action and manually add the `-h/--help` option
parser.register("action", "help", _CustomHelpAction)
parser.add_argument("-h", "--help", action="help", help="show this help message and exit")

# Add remaining arguments
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

示例用法:

所有帮助:

python3 script.py --help
usage: script.py [-h] [--url URL] [--port PORT] [--timeout TIMEOUT]

optional arguments:
  -h, --help
  --url URL          URL to the resource
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

特定参数:

~ python3 script.py -h --url --timeout
usage: script.py [--url URL] [--timeout TIMEOUT]

optional arguments:
  --url URL          URL to the resource
  --timeout TIMEOUT  Connection timeout
~ python3 script.py -h --timeout --port
usage: script.py [--timeout TIMEOUT] [--port PORT]

optional arguments:
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

这天真地假设您只使用 sys.argv,我不太确定如果不是,需要做什么。

You can create your own actions to achieve this. Both of these will iterate the optional arguments and suppress any that are not found in sys.argv. I'd recommend the explain action as this doesn't mess with the -h/--help flag.

Explain Action

This creates an action ExplainParamsAction with the corresponding -e/--explain options that filters the help text for just specified parameters.

import sys
import argparse

class ExplainParamsAction(argparse.Action):
    def __init__(
        self,
        option_strings,
        dest=argparse.SUPPRESS,
        default=argparse.SUPPRESS,
        **kwargs
    ):
        super().__init__(option_strings, dest, default=default, nargs=0, **kwargs)

    def __call__(self, parser, namespace, values, option_string=None):
        opts = parser._option_string_actions
        for arg in opts:
            if arg not in sys.argv:
                setattr(opts[arg], "help", argparse.SUPPRESS)
        parser.print_help()
        parser.exit()

parser = argparse.ArgumentParser()
parser.add_argument(
    "-e",
    "--explain",
    action=ExplainParamsAction,
    help="Show help message for only specified parameters and exit",
)
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

Override the Help Action

Alternatively you can override the help action that you supply to your parser.
To use with an argparse.ArgumentParser you need to turn off the default helper and provide your own.

import sys
import argparse

class _CustomHelpAction(argparse._HelpAction):
    def __call__(self, parser, namespace, values, option_string=None):
        args = sys.argv[1:]
        opts = parser._option_string_actions
        # Check is needed for just -h/--help to work
        if len(args) > 1:
            for arg in opts:
                if arg not in args:
                    setattr(opts[arg], "help", argparse.SUPPRESS)
        super().__call__(parser, namespace, values, option_string)


# Init parser with help turned off
parser = argparse.ArgumentParser(add_help=False)

# Register your help action and manually add the `-h/--help` option
parser.register("action", "help", _CustomHelpAction)
parser.add_argument("-h", "--help", action="help", help="show this help message and exit")

# Add remaining arguments
parser.add_argument("--url", help="URL to the resource")
parser.add_argument("--port", help="Port to the resource")
parser.add_argument("--timeout", help="Connection timeout")
args = parser.parse_args()

Example usage:

All help:

python3 script.py --help
usage: script.py [-h] [--url URL] [--port PORT] [--timeout TIMEOUT]

optional arguments:
  -h, --help
  --url URL          URL to the resource
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

Specific parameters:

~ python3 script.py -h --url --timeout
usage: script.py [--url URL] [--timeout TIMEOUT]

optional arguments:
  --url URL          URL to the resource
  --timeout TIMEOUT  Connection timeout
~ python3 script.py -h --timeout --port
usage: script.py [--timeout TIMEOUT] [--port PORT]

optional arguments:
  --port PORT        Port to the resource
  --timeout TIMEOUT  Connection timeout

This naively assumes that you are only using sys.argv, I'm not really sure what would need to be done if it weren't.

葬心 2025-01-16 05:15:03

这已经在这里讨论过:自定义argparse帮助消息

本质上,您可以通过添加来覆盖帮助--help 作为参数。

编辑:自定义帮助可能指向获取特定参数帮助的语法,例如 -sparameter_you_wish_help_about。

编辑2:还没有测试过,但有类似的情况。

parser.add_argument('-s',action='store',dest='para', type=str, help='Get Help on specific parameter')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='Use -s to get help on specific parameter')

help_dict={}
help_dict['para_1']='Help on para_1'
print (help_dict[args.para])

This has been discussed here: Customize argparse help message

In essence, you can overwrite the help by adding --help as argument.

Edit: the custom help could be pointing to a syntax for getting help on a specific parameter like -s parameter_you_wish_help_about.

Edit 2: Haven't tested it, but something along this lines.

parser.add_argument('-s',action='store',dest='para', type=str, help='Get Help on specific parameter')
parser.add_argument('-h', '--help', action='help', default=argparse.SUPPRESS, help='Use -s to get help on specific parameter')

help_dict={}
help_dict['para_1']='Help on para_1'
print (help_dict[args.para])
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文