argparse 添加示例用法

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

我使用argparse来处理输入参数,它使用parser.print_help()输出以下内容:

optional arguments:
  -h, --help            show this help message and exit
  -t TEMPLATES, --templates TEMPLATES
                    template names to make, should be defined as section
                    name in conf, and have related file in templates/
                    folder
  -c CONFPATH, --confpath CONFPATH
                    configuration path for template detail info

我的代码如下所示:

    import argparse
    parser = argparse.ArgumentParser(prog='base_maker', description='template maker')
    parser.add_argument('-t', '--templates', help='template names to make, should be defined as section name in conf, and have related file in templates/ folder', type=str)
    parser.add_argument('-c', '--confpath', help='configuration path for template detail info', type=str, default=os.path.join(basepath, 'conf/maker.conf'))

但是,我想添加一个关于如何使用 -t/--template 的详细示例,例如(在 example 部分添加):

optional arguments:
  -h, --help            show this help message and exit
  -t TEMPLATES, --templates TEMPLATES
                    template names to make, should be defined as section
                    name in conf, and have related file in templates/
                    folder
  -c CONFPATH, --confpath CONFPATH
                    configuration path for template detail info

 example:

     python test.py -t template/test.py
     python test.py -t template/test -c conf/test.conf
     python test.py -t test.py

我不知道应该使用哪个属性来添加“example”部分,我检查了Print program using example with argparse modulen,但是当我检查官方文档中的epilog时,不清楚并且没有详细的示例。

有人可以给我一个关于如何实现这一目标的例子吗?谢谢

python argparse
1个回答
54
投票

如果您希望在末尾打印示例帮助(epilog)并保留空格/格式(formatter_class 设置为 RawDescriptionHelpFormatter),则需要使用 ArgumentParser 的 epilog 和 formatter_class 参数。

通过修改上面的示例来举例:

import argparse

example_text = '''example:

 python %(prog)s -t template/test.py
 python %(prog)s -t template/test -c conf/test.conf
 python %(prog)s -t test.py'''

parser = argparse.ArgumentParser(prog='base_maker',
                                 description='template maker',
                                 epilog=example_text,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)

parser.add_argument('-t', '--templates', help='template names to make, should be defined as section name in conf, and have related file in templates/ folder', type=str)
parser.add_argument('-c', '--confpath', help='configuration path for template detail info', type=str, default=os.path.join(basepath, 'conf/maker.conf'))
© www.soinside.com 2019 - 2024. All rights reserved.