使用 argparse 模块打印程序使用示例 [英] Print program usage example with argparse module
问题描述
我正在尝试学习如何使用 python 的 argparse
模块.目前我的python脚本是:
I am trying to learn how to use python's argparse
module. Currently my python script is:
parser = argparse.ArgumentParser(description='My first argparse attempt',
add_help=True)
parser.add_argument("-q", action ="store", dest='argument',
help="First argument")
output = parser.parse_args()
它给出的输出为:
usage: test.py [-h] [-q ARGUMENT]
My first argparse attempt
optional arguments:
-h, --help show this help message and exit
-q ARGUMENT First argument
现在,假设我希望我的 -h 或 --help
参数也打印一个 用法示例
.喜欢,
Now, lets suppose I want my -h or --help
argument to print a usage example
also. Like,
Usage: python test.py -q "First Argument for test.py"
我的目的是将上面的用法示例连同-h
参数的默认内容一起打印出来,以便用户可以基本了解如何使用test.py代码> python 脚本.
My purpose is to print the above usage example along with the default content of -h
argument so that the user can get a basic idea of how to use the test.py
python script.
那么,此功能是否内置在 argparse
模块中.如果不是,那么解决这个问题的正确方法是什么.
So, is this functionality inbuilt in the argparse
module. If no than what is the correct way to approach this problem.
推荐答案
使用 parser.epilog
在生成的 -h
文本之后显示一些东西.
Use parser.epilog
to display something after the generated -h
text.
parser = argparse.ArgumentParser(
description='My first argparse attempt',
epilog='Example of use')
output = parser.parse_args()
印刷品:
My first argparse attempt
optional arguments:
-h, --help show this help message and exit
Example of use
这篇关于使用 argparse 模块打印程序使用示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!