我使用 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 时,不清楚并且没有详细的例子.
任何人都可以给我一个关于如何实现这一目标的例子吗?谢谢
最佳答案
如果您希望帮助示例打印在末尾(结尾)并保留空白/格式(formatter_class 设置为 RawDescriptionHelpFormatter),则需要使用 ArgumentParser 的结尾和 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'))
关于python - argparse 添加示例用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40419139/