Python中argparse用法

python argparse用法总结

1.argparse介绍

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

2.基本用法

prog.py 是测试argparse的文件 内容如下:

#! /usr/bin/env python3

# encoding:utf-8

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

测试:

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py  --help
usage: prog.py [-h]

optional arguments:
  -h, --help  show this help message and exit
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py  -v
usage: prog.py [-h]
prog.py: error: unrecognized arguments: -v
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py foo
usage: prog.py [-h]
prog.py: error: unrecognized arguments: foo
  • 第一个没有任何输出和出错
  • 第二个测试为打印帮助信息,argparse会自动生成帮助文档
  • 第三个测试为未定义的-v参数,会出错
  • 第四个测试为未定义的参数foo,出错

3.positional arguments

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

#! /usr/bin/env python3

# encoding:utf-8

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print(args.echo)

执行测试如下

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py -h
usage: prog.py [-h] echo

positional arguments:
  echo

optional arguments:
  -h, --help  show this help message and exit
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py lalal
lalal

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

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

4.optional arguments

中文名叫 可选参数 有两种方式: * 通过-来指定的短参数 * 通过--来指定的长参数

#!/usr/bin/env python
# encoding: utf-8


import argparse


parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
        print "verbosity turned on"

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

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py -v 1
verbosity turned on
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py --verbosity 1
verbosity turned on
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py -h
usage: prog.py [-h] [-v VERBOSITY]

optional arguments:
  -h, --help            show this help message and exit
  -v VERBOSITY, --verbosity VERBOSITY
                        increase output verbosity
bokaideMacBook-Pro:python100 bokaichen$ python3 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’

利用action = "store_true -v 没有参数时不会报错

6.类型type

默认的参数类型为str,如果要进行数学计算 需要对参数进行解析后进行类型转换 如果不能转换则需要报错 这样比较麻烦

argparse提供了对参数类型的解析,如果类型不符合,则直接报错

#!/usr/bin/env python3
# encoding: utf-8


import argparse


parser = argparse.ArgumentParser()
parser.add_argument('x', type=int, help="the base")
args = parser.parse_args()
answer = args.x ** 2
print(answer)

测试:

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 2
4
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py two
usage: prog.py [-h] x
prog.py: error: argument x: invalid int value: 'two'
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py -h
usage: prog.py [-h] x

positional arguments:
  x           the base

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

7.可选值choices=[]

#!/usr/bin/env python3
# encoding: utf-8


import argparse


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

测试:

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 -v 0
16
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 -v 1
4^2 == 16
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 -v 2
the square of 4 equals 16
bokaideMacBook-Pro:python100 bokaichen$ python3 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)
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 -h
usage: prog.py [-h] [-v {0,1,2}] square

positional arguments:
  square                display a square of a given number

optional arguments:
  -h, --help            show this help message and exit
  -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 a square of a given number

9.程序用法帮助

通过argparse.ArgumentParser(description="calculate X to the power of Y") 为整个程序定义帮助文档

bokaideMacBook-Pro:python100 bokaichen$ python3 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, --help     show this help message and exit
  -v, --verbose
  -q, --quiet

10.互斥参数

互斥的参数

group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")

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

bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 2
4^2 == 16
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 2 -v
4 to the power 2 equals 16
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 2 -q
16
bokaideMacBook-Pro:python100 bokaichen$ python3 prog.py 4 2 -q -v
usage: prog.py [-h] [-v | -q] x y
prog.py: error: argument -v/--verbose: not allowed with argument -q/--quiet

11.参数默认值

参数默认值定义

#!/usr/bin/env python3
# encoding: utf-8


import argparse


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

测试结果:

bokaideMacBook-Pro:python100 bokaichen$ python prog.py 8
8^2 == 64
bokaideMacBook-Pro:python100 bokaichen$ python prog.py 8 -v 0
64
bokaideMacBook-Pro:python100 bokaichen$ python prog.py 8 -v 1
8^2 == 64
bokaideMacBook-Pro:python100 bokaichen$ python prog.py 8 -v 2
the square of 8 equals 64

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

点击刷新