Yoa*_*yun 9 python python-2.7 argparse python-3.x
我正在使用python的argparse来处理参数的解析.我得到一个默认的帮助消息,结构如下:
usage: ProgramName [-h] ...
Description
positional arguments:
...
optional arguments:
-h, --help show this help message and exit
...
Run Code Online (Sandbox Code Playgroud)
我想要的是在此消息中添加一个全新的部分,例如:
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.
....
Run Code Online (Sandbox Code Playgroud)
有没有办法实现这种行为?python 2.7和3.x都支持的解决方案是首选.
编辑:我还希望有一个解决方案,将在帮助消息的底部添加新的部分/部分.
小智 14
你可以使用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()
Run Code Online (Sandbox Code Playgroud)
结果:
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
Run Code Online (Sandbox Code Playgroud)
您可以通过多种方式向命令添加描述。推荐的方法是在源代码文件的顶部添加模块文档,如下所示:
""" This is the description, it will be accessible within the variable
__doc__
"""
Run Code Online (Sandbox Code Playgroud)
然后:
parser = argparse.ArgumentParser(description=__doc__)
Run Code Online (Sandbox Code Playgroud)
要在参数描述下方添加文本,请使用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
Run Code Online (Sandbox Code Playgroud)
有关更多信息,请参阅文档(上面链接)。