带有argparse模块的打印程序用法示例 [英] Print program usage example with argparse module

查看:80
本文介绍了带有argparse模块的打印程序用法示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习如何使用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 or --help自变量也打印一个usage example.喜欢,

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆