简介[^1]

通俗来说,命令行与参数解析就是当你输入cmd 打开dos 交互界面时候,启动程序要进行的参数给定。比如在dos 界面输入:python openPythonFile.py "a" -b "number",其中的”a”, -b 等就是命令行与参数解析要做的事。

基本框架

  • 创建解析
  • 添加参数
  • 解析参数
1
2
3
4
5
6
7
8
9
10
11
12
13
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')
# 解析参数步骤
args = parser.parse_args()
print(args.accumulate(args.integers))

参数设定[^1]

创建解析

1
ArgumentParser(prog='', usage=None, description='Process some integers.', version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=True)
  • prog
  • usage
  • description
  • epilog
  • parents
  • formatter_class
  • prefix_chars
  • conflict_handler
  • add_help

添加参数

  • 每一个参数都要单独设置,需要两个参数就用两个add_argument 。
  • 参数分为两种:positional arguments 和optional arguments
    • positional arguments 参数按照参数设置的先后顺序对应读取,实际中不用设置参数名,必须有序设计。
    • optional arguments 参数在使用时必须使用参数名,然后是参数具体数值,设置可以是无序的。
  • 程序根据prefix_chars(默认”-“)自动识别positional arguments 还是optional arguments。且prefix_chars 分为缩写(比如”-h“)和对应的全程(比如”–help“),可以同时设置
1
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
  • name or flags :以’-‘为前缀的参数为optional arguments,其余为positional arguments
  • action :命令行参数的操作。
  • count :统计出现的次数。
  • help
  • version
  • nrgs
  • const
  • default
  • type
  • choices
  • required
  • desk
  • metavar

解析参数

1
2
3
4
5
6
7
8
9
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('x')
>>> a = parser.parse_args(['1'])
>>> a
Namespace(x='1')
>>> type(a)
<class 'argparse.Namespace'>
>>> a.x
'1'

例子

filename = argv_argparse.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sys
import argparse

def cmd():
args = argparse.ArgumentParser(description = 'Personal Information ',epilog = 'Information end ')
#必写属性,第一位
args.add_argument("name", type = str, help = "Your name")
#必写属性,第二位
args.add_argument("birth", type = str, help = "birthday")
#可选属性,默认为None
args.add_argument("-r",'--race', type = str, dest = "race", help = u"民族")
#可选属性,默认为0,范围必须在0~150
args.add_argument("-a", "--age", type = int, dest = "age", help = "Your age", default = 0, choices=range(150))
#可选属性,默认为male
args.add_argument('-s',"--sex", type = str, dest = "sex", help = 'Your sex', default = 'male', choices=['male', 'female'])
#可选属性,默认为None,-p后可接多个参数
args.add_argument("-p","--parent",type = str, dest = 'parent', help = "Your parent", default = "None", nargs = '*')
#可选属性,默认为None,-o后可接多个参数
args.add_argument("-o","--other", type = str, dest = 'other', help = "other Information",required = False,nargs = '*')

args = args.parse_args()#返回一个命名空间,如果想要使用变量,可用args.attr
print "argparse.args=",args,type(args)
print 'name = %s'%args.name
d = args.__dict__
for key,value in d.iteritems():
print '%s = %s'%(key,value)

if __name__=="__main__":
cmd()

dos输入命令示例:

1
2
3
python argv_argparse.py -h
python argv_argparse.py xiaoming 1991.11.11
python argv_argparse.py xiaoming 1991.11.11 -p xiaohong xiaohei -a 25 -r han -s female -o 1 2 3 4 5 6

[^1]: Python-argparse-命令行与参数解析
[^2]: Argparse Tutorial
[^3]: python argparse用法总结