[英]Python Argparse - How can I add text to the default help message?
我正在使用python的argparse来处理参数的解析。 我得到一个默认的帮助消息,结构如下:
usage: ProgramName [-h] ...
Description
positional arguments:
...
optional arguments:
-h, --help show this help message and exit
...
我想要的是在此消息中添加一个全新的部分,例如:
usage: ProgramName [-h] ...
Description
positional arguments:
...
optional arguments:
-h, --help show this help message and exit
...
additional information:
This will show additional information relevant to the user.
....
有没有办法实现这种行为? python 2.7和3.x都支持的解决方案是首选。
编辑:我还希望有一个解决方案,将在帮助消息的底部添加新的部分/部分。
你可以使用epilog完成它。 以下是一个示例:
import argparse
import textwrap
parser = argparse.ArgumentParser(
prog='ProgramName',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=textwrap.dedent('''\
additional information:
I have indented it
exactly the way
I want it
'''))
parser.add_argument('--foo', nargs='?', help='foo help')
parser.add_argument('bar', nargs='+', help='bar help')
parser.print_help()
结果:
usage: ProgramName [-h] [--foo [FOO]] bar [bar ...]
positional arguments:
bar bar help
optional arguments:
-h, --help show this help message and exit
--foo [FOO] foo help
additional information:
I have indented it
exactly the way
I want it
您可以通过多种方式向命令添加说明 。 建议的方法是在源代码文件的顶部添加模块文档,如下所示:
""" This is the description, it will be accessible within the variable
__doc__
"""
然后:
parser = argparse.ArgumentParser(description=__doc__)
要在参数说明下添加文本,请使用epilog,如以下示例所示:
>>> parser = argparse.ArgumentParser(description='A foo that bars',
epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: argparse.py [-h]
A foo that bars
optional arguments: -h, --help show this help message and exit
And that's how you'd foo a bar
有关更多信息,请参阅文档(上面链接)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.