Python argparse:有没有办法只打印特定参数的帮助?
我有一个很长的参数列表,因此 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建自己的操作来实现这一目标。这两个都将迭代可选参数并抑制 sys.argv 中未找到的任何参数。我建议使用解释操作,因为这不会与
-h/--help
标志混淆。解释操作
这将创建一个带有相应
-e/--explain
选项的操作ExplainParamsAction
,该选项可过滤仅指定参数的帮助文本。覆盖帮助操作
或者,您可以覆盖提供给解析器的帮助操作。
与
argparse.ArgumentParser
你需要关闭默认的助手并提供你自己的。示例用法:
所有帮助:
特定参数:
这天真地假设您只使用 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.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.Example usage:
All help:
Specific parameters:
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.这已经在这里讨论过:自定义argparse帮助消息
本质上,您可以通过添加来覆盖帮助--help 作为参数。
编辑:自定义帮助可能指向获取特定参数帮助的语法,例如 -sparameter_you_wish_help_about。
编辑2:还没有测试过,但有类似的情况。
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.