程序猿阵线联盟-汇总各类技术干货python自学Python时空大数据

Python命令行解析器argparse的使用

2018-10-19  本文已影响13人  Sui_Xin

本文首发于我的个人博客 Suixin's Blog

argparse是Python内置的一个用于命令项选项与参数解析的模块,在编写脚本的过程中是非常常用的。
在其使用中主要包含三个步骤:

import argparse


parser = argparse.ArgumentParser(description='this is a process for read file')
parser.add_argument('fileinPath', help='path to input file')
parser.add_argument('fileoutPath', help='path to output file')
args = parser.parse_args()

而当如上定义后,即可在需要用到参数的地方调用args.fileinPathargs.fileoutPath。下面详细讲解一下add_argument()方法。

add_argument()方法

位置参数

位置参数是必选参数,如果命令行解析不到就会报错,上面例子中两个参数都是位置参数。

可选参数

可选参数可以填写两种,长的可选参数以及短的,并且可以并存,会首先解析长可选参数。如:

parser.add_argument('-s', '--square', help='display a square of a given number', type=int)

当然在一个脚本中,位置参数与可选参数是可以并存的。

一个例子

给一个整数序列,输出它们的和或最大值(默认)

import argparse


parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
                   help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
                   const=sum, default=max,
                   help='sum the integers (default: find the max)')
args = parser.parse_args()

print(args.accumulate(args.integers))

则在调用的时候:

>>> python test.py
usage: test.py [-h] [--sum] N [N ...]
test.py: error: the following arguments are required: N
>>> python test.py -h
usage: test.py [-h] [--sum] N [N ...]

Process some integers.

positional arguments:
  N           an integer for the accumulator

optional arguments:
  -h, --help  show this help message and exit
  --sum       sum the integers (default: find the max)
>>> python test.py 1 2 3 4
4
>>> python test.py 1 2 3 4 --sum
10

所有参数

参考

http://wiki.jikexueyuan.com/project/explore-python/Standard-Modules/argparse.html
https://docs.python.org/3/library/argparse.html#the-add-argument-method

上一篇 下一篇

猜你喜欢

热点阅读