argparse添加示例用法

时间:2016-11-04 09:27:43

标签: python argparse

我使用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的详细示例,如(在示例部分中添加):

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

我不知道应该使用哪个属性添加"示例"部分,我检查Print program usage example with argparse modulen,但当我检查epilog in the official doc时,它不清楚且没有详细示例。

有人能给我一个如何实现这个目标的例子吗?感谢

1 个答案:

答案 0 :(得分:17)

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

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

import argparse

example_text = '''example:

 python test.py -t template/test.py
 python test.py -t template/test -c conf/test.conf
 python test.py -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'))