python argparse用法

2,136次阅读
没有评论

博主的python也是很烂,所以最近再看500lines or less 一个很不错的专题,可以熟悉python基本知识,也是查看自己掌握的扎实不扎实,值得一看

1. argparse介绍

是python的一个命令行解析包,非常编写可读性非常好的程序

2. 基本用法

prog.py是我在linux下测试argparse的文件,放在/tmp目录下,其内容如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse
parser = argparse.ArgumentParser()
parser.parse_args()

测试:

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 

yarving@yarving-VirtualBox /tmp</span> python prog.py --<span class="hljs-built_in">help</span>
usage: prog.py [-h]

optional arguments:
  -h, --<span class="hljs-built_in">help</span>  show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py -v 
usage: prog.py [-h]
prog.py: error: unrecognized arguments: -v

yarving@yarving-VirtualBox /tmp</span> python prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
  • 第一个没有任何输出和出错
  • 第二个测试为打印帮助信息,argparse会自动生成帮助文档
  • 第三个测试为未定义的-v参数,会出错
  • 第四个测试为未定义的参数foo,出错

3. positional arguments

positional arguments为英文定义,中文名叫有翻译为定位参数的,用法是不用带-就可用 修改prog.py的内容如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">"echo"</span>)
args = parser.parse_args()
<span class="hljs-keyword">print</span> args.echo

执行测试如下

yarving@yarving-VirtualBox /tmp $ python prog.py   
usage: prog.py [-h] <span class="hljs-built_in">echo</span>
prog.py: error: too few arguments

yarving@yarving-VirtualBox /tmp $ python prog.py -h
usage: prog.py [-h] <span class="hljs-built_in">echo</span>

positional arguments:
  <span class="hljs-built_in">echo</span>

optional arguments:
  -h, --<span class="hljs-built_in">help</span>  show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>

yarving@yarving-VirtualBox /tmp $ python prog.py hahahaha
hahahaha

定义了一个叫echo的参数,默认必选

  • 第一个测试为不带参数,由于echo参数为空,所以报错,并给出用法(usage)和错误信息
  • 第二个测试为打印帮助信息
  • 第三个测试为正常用法,回显了输入字符串hahahaha

4. optional arguments

中文名叫可选参数,有两种方式:

  1. 一种是通过一个-来指定的短参数,如-h
  2. 一种是通过--来指定的长参数,如--help

这两种方式可以同存,也可以只存在一个,修改prog.py内容如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbosity"</span>, help=<span class="hljs-string">"increase output verbosity"</span>)
args = parser.parse_args()
<span class="hljs-keyword">if</span> args.verbosity:
        <span class="hljs-keyword">print</span> <span class="hljs-string">"verbosity turned on"</span>

注意这一行:parser.add_argument("-v", "--verbosity", help="increase output verbosity") 定义了可选参数-v--verbosity,通过解析后,其值保存在args.verbosity变量中 用法如下:

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py -v 1
verbosity turned on

yarving@yarving-VirtualBox /tmp</span> python prog.py --verbosity 1
verbosity turned on

yarving@yarving-VirtualBox /tmp $ python prog.py -h           
usage: prog.py [-h] [-v VERBOSITY]

optional arguments:
  -h, --<span class="hljs-built_in">help</span>            show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>
  -v VERBOSITY, --verbosity VERBOSITY
                        increase output verbosity

yarving@yarving-VirtualBox /tmp $ python prog.py -v 
usage: prog.py [-h] [-v VERBOSITY]
prog.py: error: argument -v/--verbosity: expected one argument
  • 测试1中,通过-v来指定参数值
  • 测试2中,通过--verbosity来指定参数值
  • 测试3中,通过-h来打印帮助信息
  • 测试4中,没有给-v指定参数值,所以会报错

5. action=’store_true’

上一个用法中-v必须指定参数值,否则就会报错,有没有像-h那样,不需要指定参数值的呢,答案是有,通过定义参数时指定action="store_true"即可,用法如下

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbose"</span>, help=<span class="hljs-string">"increase output verbosity"</span>,
                    action=<span class="hljs-string">"store_true"</span>)
args = parser.parse_args()
<span class="hljs-keyword">if</span> args.verbose:
        <span class="hljs-keyword">print</span> <span class="hljs-string">"verbosity turned on"</span>

测试:

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py -v
verbosity turned on

yarving@yarving-VirtualBox /tmp</span> python prog.py -h
usage: prog.py [-h] [-v]

optional arguments:
  -h, --<span class="hljs-built_in">help</span>     show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>
  -v, --verbose  increase output verbosity

第一个例子中,-v没有指定任何参数也可,其实存的是TrueFalse,如果出现,则其值为True,否则为False

6. 类型 type

默认的参数类型为str,如果要进行数学计算,需要对参数进行解析后进行类型转换,如果不能转换则需要报错,这样比较麻烦 argparse提供了对参数类型的解析,如果类型不符合,则直接报错。如下是对参数进行平方计算的程序:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">'x'</span>, type=int, help=<span class="hljs-string">"the base"</span>)
args = parser.parse_args()
answer = args.x ** <span class="hljs-number">2</span>
<span class="hljs-keyword">print</span> answer

测试

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 2
4

yarving@yarving-VirtualBox /tmp</span> python prog.py two
usage: prog.py [-h] x
prog.py: error: argument x: invalid int value: <span class="hljs-string">'two'</span>

yarving@yarving-VirtualBox /tmp $ python prog.py -h 
usage: prog.py [-h] x

positional arguments:
  x           the base

optional arguments:
  -h, --<span class="hljs-built_in">help</span>  show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>
  • 第一个测试为计算2的平方数,类型为int,正常
  • 第二个测试为一个非int数,报错
  • 第三个为打印帮助信息

7. 可选值choices=[]

5中的action的例子中定义了默认值为TrueFalse的方式,如果要限定某个值的取值范围,比如6中的整形,限定其取值范围为0, 1, 2,该如何进行呢? 修改prog.py文件如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser()
parser.add_argument(<span class="hljs-string">"square"</span>, type=int,
                    help=<span class="hljs-string">"display a square of a given number"</span>)
parser.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbosity"</span>, type=int, choices=[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>],
                    help=<span class="hljs-string">"increase output verbosity"</span>)
args = parser.parse_args()
answer = args.square**<span class="hljs-number">2</span>
<span class="hljs-keyword">if</span> args.verbosity == <span class="hljs-number">2</span>:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"the square of {} equals {}"</span>.format(args.square, answer)
<span class="hljs-keyword">elif</span> args.verbosity == <span class="hljs-number">1</span>:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"{}^2 == {}"</span>.format(args.square, answer)
<span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">print</span> answer

测试如下:

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 4 -v 0
16
yarving@yarving-VirtualBox /tmp</span> python prog.py 4 -v 1
4^2 == 16
yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 4 -v 2
the square of 4 equals 16
yarving@yarving-VirtualBox /tmp</span> python prog.py 4 -v 3
usage: prog.py [-h] [-v {0,1,2}] square
prog.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
yarving@yarving-VirtualBox /tmp $ python prog.py -h
usage: prog.py [-h] [-v {0,1,2}] square

positional arguments:
  square                display a square of a given number

optional arguments:
  -h, --<span class="hljs-built_in">help</span>            show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>
  -v {0,1,2}, --verbosity {0,1,2}
                        increase output verbosity
  • 测试1, 2, 3 为可选值范围,通过其值,打印不同的格式输出;
  • 测试4的verbosity值不在可选值范围内,打印错误
  • 测试5打印帮助信息

8. 自定义帮助信息help

上面很多例子中都为help赋值,如 parser.add_argument("square", type=int, help="display a square of a given number") 在打印输出时,会有如下内容

positional arguments:
  square                display <span class="hljs-keyword">a</span> square <span class="hljs-keyword">of</span> <span class="hljs-keyword">a</span> given <span class="hljs-built_in">number</span>

也就是help为什么,打印输出时,就会显示什么

9. 程序用法帮助

8中介绍了为每个参数定义帮助文档,那么给整个程序定义帮助文档该怎么进行呢? 通过argparse.ArgumentParser(description="calculate X to the power of Y")即可 修改prog.py内容如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser(description=<span class="hljs-string">"calculate X to the power of Y"</span>)
group = parser.add_mutually_exclusive_group()
group.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbose"</span>, action=<span class="hljs-string">"store_true"</span>)
group.add_argument(<span class="hljs-string">"-q"</span>, <span class="hljs-string">"--quiet"</span>, action=<span class="hljs-string">"store_true"</span>)
parser.add_argument(<span class="hljs-string">"x"</span>, type=int, help=<span class="hljs-string">"the base"</span>)
parser.add_argument(<span class="hljs-string">"y"</span>, type=int, help=<span class="hljs-string">"the exponent"</span>)
args = parser.parse_args()
answer = args.x**args.y

<span class="hljs-keyword">if</span> args.quiet:
    <span class="hljs-keyword">print</span> answer
<span class="hljs-keyword">elif</span> args.verbose:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"{} to the power {} equals {}"</span>.format(args.x, args.y, answer)
<span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"{}^{} == {}"</span>.format(args.x, args.y, answer)

打印帮助信息时即显示calculate X to the power of Y

yarving@yarving-VirtualBox /tmp $ python prog.py -h
usage: prog.py [-h] [-v | -q] x y

calculate X to the power of Y

positional arguments:
  x              the base
  y              the exponent

optional arguments:
  -h, --<span class="hljs-built_in">help</span>     show this <span class="hljs-built_in">help</span> message and <span class="hljs-built_in">exit</span>
  -v, --verbose
  -q, --quiet

10. 互斥参数

在上个例子中介绍了互斥的参数

<span class="hljs-built_in">group</span> = parser.add_mutually_exclusive_group()
<span class="hljs-built_in">group</span>.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbose"</span>, <span class="hljs-built_in">action</span>=<span class="hljs-string">"store_true"</span>)
<span class="hljs-built_in">group</span>.add_argument(<span class="hljs-string">"-q"</span>, <span class="hljs-string">"--quiet"</span>, <span class="hljs-built_in">action</span>=<span class="hljs-string">"store_true"</span>)

第一行定义了一个互斥组,第二、三行在互斥组中添加了-v-q两个参数,用上个例子中的程序进行如下测试:

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 4 2      
4^2 == 16
yarving@yarving-VirtualBox /tmp</span> python prog.py 4 2 -v
4 to the power 2 equals 16
yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 4 2 -q
16
yarving@yarving-VirtualBox /tmp</span> python prog.py 4 2 -q -v

可以看出,-q-v不出现,或仅出现一个都可以,同时出现就会报错。 可定义多个互斥组

11.参数默认值

介绍了这么多,有没有参数默认值该如何定义呢? 修改prog.py内容如下:

<span class="hljs-comment">#!/usr/bin/env python</span>
<span class="hljs-comment"># encoding: utf-8</span>


<span class="hljs-keyword">import</span> argparse


parser = argparse.ArgumentParser(description=<span class="hljs-string">"calculate X to the power of Y"</span>)
parser.add_argument(<span class="hljs-string">"square"</span>, type=int,
                    help=<span class="hljs-string">"display a square of a given number"</span>)
parser.add_argument(<span class="hljs-string">"-v"</span>, <span class="hljs-string">"--verbosity"</span>, type=int, choices=[<span class="hljs-number">0</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2</span>], default=<span class="hljs-number">1</span>,
                    help=<span class="hljs-string">"increase output verbosity"</span>)
args = parser.parse_args()
answer = args.square**<span class="hljs-number">2</span>
<span class="hljs-keyword">if</span> args.verbosity == <span class="hljs-number">2</span>:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"the square of {} equals {}"</span>.format(args.square, answer)
<span class="hljs-keyword">elif</span> args.verbosity == <span class="hljs-number">1</span>:
    <span class="hljs-keyword">print</span> <span class="hljs-string">"{}^2 == {}"</span>.format(args.square, answer)
<span class="hljs-keyword">else</span>:
    <span class="hljs-keyword">print</span> answer

测试结果如下

yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 8 
8^2 == 64
yarving@yarving-VirtualBox /tmp</span> python prog.py 8 -v 0
64
yarving@yarving-VirtualBox /tmp <span class="katex math inline">python prog.py 8 -v 1
8^2 == 64
yarving@yarving-VirtualBox /tmp</span> python prog.py 8 -v 2
the square of 8 equals 64

可以看到如果不指定-v的值,args.verbosity的值默认为1,为了更清楚的看到默认值,也可以直接打印进行测试。

链接:http://www.jianshu.com/p/fef2d215b91d

admin
版权声明:本站原创文章,由admin2017-07-23发表,共计7276字。
转载提示:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)