argparse 添加示例用法

argparse add example usage

我使用 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

我不知道应该使用哪个属性来添加"example"部分,我检查了Print program usage example with argparse modulen, but it's unclear and without detailed example when I check epilog in the official doc

任何人都可以给我一个关于如何实现这一点的例子吗?谢谢

如果你想在最后打印示例的帮助(epilog)并保留 whitespace/formatting(formatter_class 设置为 RawDescriptionHelpFormatter)。

修改上面的例子的例子:

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'))