在编程语言中我们经常需要从命令行读取参数,解析参数的方式多种多样。
第一种:直接给定
这种方法虽然实现起来方便,但是灵活性非常差,每次都需要打开python文件修改参数。
第二种: 手动解析
import sys
def TestSys():
for arg in sys.argv[1: ] : #对输入的第二个参数到最后,arg[0] 为第一个参数
print arg
第三种:自动解析(这里就要用到Python中的argparse模块,本篇文章也是主要讲这个模块)
1.创建解析器
import argparse
parser = argparse.ArgumentParser()
创建一个ArgumentParser实例对象,ArgumentParser对象的参数都为关键字参数
class ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
prog:程序的名字,默认为sys.argv[0],用来在help信息中描述程序的名称。
1
2
3
4
5
6
|
>>>
parser = argparse.ArgumentParser(prog= 'myprogram' ) >>>
parser.print_help() usage:
myprogram [-h] optional
arguments: -h,
--help show this help
message and exit |
usage:描述程序用途的字符串
1
2
3
4
5
6
7
8
9
10
11
12
|
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ,
usage= '%(prog)s
[options]' ) >>>
parser.add_argument( '--foo' ,
nargs= '?' ,
help= 'foo
help' ) >>>
parser.add_argument( 'bar' ,
nargs= '+' ,
help= 'bar
help' ) >>>
parser.print_help() usage:
PROG [options] positional
arguments: bar
bar help optional
arguments: -h,
--help show this help
message and exit --foo
[FOO] foo help |
description:help信息前的文字。
epilog:help信息之后的信息
1
2
3
4
5
6
7
8
9
10
11
12
|
>>>
parser = argparse.ArgumentParser( ...
description= 'A
foo that bars' , ...
epilog= "And
that's how you'd foo a bar" ) >>>
parser.print_help() usage:
argparse.py [-h] A
foo that bars optional
arguments: -h,
--help show this help
message and exit And
that 's
how you' d
foo a bar |
parents:由ArgumentParser对象组成的列表,它们的arguments选项会被包含到新ArgumentParser对象中。
1
2
3
4
5
6
7
|
>>>
parent_parser = argparse.ArgumentParser(add_help=False) >>>
parent_parser.add_argument( '--parent' ,
type= int ) >>>
foo_parser = argparse.ArgumentParser(parents=[parent_parser]) >>>
foo_parser.add_argument( 'foo' ) >>>
foo_parser.parse_args([ '--parent' , '2' , 'XXX' ]) Namespace(foo= 'XXX' ,
parent=2) |
formatter_class:help信息输出的格式,
prefix_chars:参数前缀,默认为'-'
1
2
3
4
5
|
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ,
prefix_chars= '-+' ) >>>
parser.add_argument( '+f' ) >>>
parser.add_argument( '++bar' ) >>>
parser.parse_args( '+f
X ++bar Y' .split()) Namespace(bar= 'Y' ,
f= 'X' ) |
fromfile_prefix_chars:前缀字符,放在文件名之前
1
2
3
4
5
6
|
>>>
with open( 'args.txt' , 'w' ) as fp: ...
fp.write( '-f\nbar' ) >>>
parser = argparse.ArgumentParser(fromfile_prefix_chars= '@' ) >>>
parser.add_argument( '-f' ) >>>
parser.parse_args([ '-f' , 'foo' , '@args.txt' ]) Namespace(f= 'bar' ) |
当参数过多时,可以将参数放到文件中读取,例子中parser.parse_args(['-f', 'foo', '@args.txt'])解析时会从文件args.txt读取,相当于['-f', 'foo', '-f', 'bar']。
argument_default:参数的全局默认值。例如,要禁止parse_args时的参数默认添加,我们可以:
1
2
3
4
5
6
7
|
>>>
parser = argparse.ArgumentParser(argument_default=argparse.SUPPRESS) >>>
parser.add_argument( '--foo' ) >>>
parser.add_argument( 'bar' ,
nargs= '?' ) >>>
parser.parse_args([ '--foo' , '1' , 'BAR' ]) Namespace(bar= 'BAR' ,
foo= '1' ) >>>
parser.parse_args() Namespace() |
当parser.parse_args()时不会自动解析foo和bar了。
conflict_handler:解决冲突的策略,默认情况下冲突会发生错误:
1
2
3
4
5
6
|
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ) >>>
parser.add_argument( '-f' , '--foo' ,
help= 'old
foo help' ) >>>
parser.add_argument( '--foo' ,
help= 'new
foo help' ) Traceback
(most recent call last): .. ArgumentError:
argument --foo: conflicting option string (s):
--foo |
我们可以设定冲突解决策略:
1
2
3
4
5
6
7
8
9
10
|
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ,
conflict_handler= 'resolve' ) >>>
parser.add_argument( '-f' , '--foo' ,
help= 'old
foo help' ) >>>
parser.add_argument( '--foo' ,
help= 'new
foo help' ) >>>
parser.print_help() usage:
PROG [-h] [-f FOO] [--foo FOO] optional
arguments: -h,
--help show this help
message and exit -f
FOO old foo help --foo
FOO new foo
help |
add_help:设为False时,help信息里面不再显示-h --help信息。
2.添加参数选项
add_argument(name
or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
a.name or flags:参数有两种,可选参数和位置参数。
添加可选参数:
1
|
>>>
parser.add_argument( '-f' , '--foo' ) |
添加位置参数:
1
|
>>>
parser.add_argument( 'bar' ) |
parse_args()运行时,会用'-'来认证可选参数,剩下的即为位置参数。
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ) >>>
parser.add_argument( '-f' , '--foo' )
#-是简写,--是全称,都可以 >>>
parser.add_argument( 'bar' )
#位置参数 >>>
parser.parse_args([ 'BAR' ])
#给位置参数赋值 Namespace(bar= 'BAR' ,
foo=None) #位置参数有值,可选参数没有值 >>>
parser.parse_args([ 'BAR' , '--foo' , 'FOO' ]) Namespace(bar= 'BAR' ,
foo= 'FOO' )
#位置参数和可选参数都有值 >>>
parser.parse_args([ '--foo' , 'FOO' ]) usage:
PROG [-h] [-f FOO] bar PROG:
error: too few arguments |
解析时没有位置参数就会报错了。
b. nargs:参数的数量
值可以为整数N(N个),*(任意多个),+(一个或更多)
1
2
3
4
5
6
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ,
nargs= '*' ) >>>
parser.add_argument( '--bar' ,
nargs= '*' ) >>>
parser.add_argument( 'baz' ,
nargs= '*' ) >>>
parser.parse_args( 'a
b --foo x y --bar 1 2' .split()) Namespace(bar=[ '1' , '2' ],
baz=[ 'a' , 'b' ],
foo=[ 'x' , 'y' ]) |
值为?时,首先从命令行获得参数,若没有则从const获得,然后从default获得:
1
2
3
4
5
6
7
8
9
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ,
nargs= '?' , const = 'c' , default = 'd' ) >>>
parser.add_argument( 'bar' ,
nargs= '?' , default = 'd' ) >>>
parser.parse_args( 'XX
--foo YY' .split()) Namespace(bar= 'XX' ,
foo= 'YY' ) >>>
parser.parse_args( 'XX
--foo' .split()) Namespace(bar= 'XX' ,
foo= 'c' ) >>>
parser.parse_args( '' .split()) Namespace(bar= 'd' ,
foo= 'd' ) |
更常用的情况是允许参数为文件
1
2
3
4
5
6
7
8
9
10
11
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( 'infile' ,
nargs= '?' ,
type=argparse.FileType( 'r' ), ... default =sys.stdin) >>>
parser.add_argument( 'outfile' ,
nargs= '?' ,
type=argparse.FileType( 'w' ), ... default =sys.stdout) >>>
parser.parse_args([ 'input.txt' , 'output.txt' ]) Namespace(infile=<open
file 'input.txt' ,
mode 'r' at
0x...>, outfile=<open
file 'output.txt' ,
mode 'w' at
0x...>) >>>
parser.parse_args([]) Namespace(infile=<open
file '<stdin>' ,
mode 'r' at
0x...>, outfile=<open
file '<stdout>' ,
mode 'w' at
0x...>) |
c.const:保存一个常量
d.default:默认值
e.type:参数类型
</pre></p><p><span style="font-size:18px;"> </span><pre name="code" class="python">#!/usr/bin/env python
# encoding: utf-8
from PIL import Image
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('file') #输入文件
parser.add_argument('-ob', '--output') #输出文件
parser.add_argument('--width', type = int,default=80) #输出字符画宽
parser.add_argument('--height', type = int,default = 80) #输出字符画高
args = parser.parse_args()
IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output
print IMG
print WIDTH
print HEIGHT
print OUTPUT
在命令行输入:python c.py ascii_dora.png -o output.txt --width 100 --height 80
得到的结果
ascii_dora.png #获得了文件名
100 #获得了输入值100
80 #获得了默认值
output.txt #获得输出文件名
f.choices:可供选择的值
>>>
parser = argparse.ArgumentParser(prog=
'doors.py'
)
>>>
parser.add_argument(
'door'
,
type=
int
,
choices=range(1, 4))
>>>
print(parser.parse_args([
'3'
]))
Namespace(door=3)
>>>
parser.parse_args([
'4'
])
usage:
doors.py [-h] {1,2,3}
doors.py:
error: argument door: invalid choice: 4 (choose
from
1,
2, 3)
g.required:是否必选
parser.add_argument('-m', required=True, choices=['new', 'continue'],
help='continue will omit downloaded data. new will start one new task')
parser.add_argument('-id', required=True,
help='id will help find path.')
h.desk:可作为参数名>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', dest='bar')
>>> parser.parse_args('--foo XXX'.split())
Namespace(bar='XXX')
i.action:默认为store
store_const,值存放在const中:
1
2
3
4
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ,
action= 'store_const' , const =42) >>>
parser.parse_args( '--foo' .split()) Namespace(foo=42) |
store_true和store_false,值存为True或False
1
2
3
4
5
6
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ,
action= 'store_true' ) >>>
parser.add_argument( '--bar' ,
action= 'store_false' ) >>>
parser.add_argument( '--baz' ,
action= 'store_false' ) >>>
parser.parse_args( '--foo
--bar' .split()) Namespace(bar=False,
baz=True, foo=True) |
append:存为列表
1
2
3
4
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ,
action= 'append' ) >>>
parser.parse_args( '--foo
1 --foo 2' .split()) Namespace(foo=[ '1' , '2' ]) |
append_const:存为列表,会根据const关键参数进行添加:
1
2
3
4
5
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--str' ,
dest= 'types' ,
action= 'append_const' , const =str) >>>
parser.add_argument( '--int' ,
dest= 'types' ,
action= 'append_const' , const = int ) >>>
parser.parse_args( '--str
--int' .split()) Namespace(types=[<type 'str' >,
<type 'int' >]) |
count:统计参数出现的次数
1
2
3
4
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--verbose' , '-v' ,
action= 'count' ) >>>
parser.parse_args( '-vvv' .split()) Namespace(verbose=3) |
help:help信息
version:版本
1
2
3
4
5
|
>>>
import argparse >>>
parser = argparse.ArgumentParser(prog= 'PROG' ) >>>
parser.add_argument( '--version' ,
action= 'version' ,
version= '%(prog)s
2.0' ) >>>
parser.parse_args([ '--version' ]) PROG
2.0 |
4.解析参数
参数有几种写法:
最常见的空格分开:
1
2
3
4
5
6
7
|
>>>
parser = argparse.ArgumentParser(prog= 'PROG' ) >>>
parser.add_argument( '-x' ) >>>
parser.add_argument( '--foo' ) >>>
parser.parse_args( '-x
X' .split()) Namespace(foo=None,
x= 'X' ) >>>
parser.parse_args( '--foo
FOO' .split()) Namespace(foo= 'FOO' ,
x=None) |
长选项用=分开
1
2
|
>>>
parser.parse_args( '--foo=FOO' .split()) Namespace(foo= 'FOO' ,
x=None) |
短选项可以写在一起:
1
2
|
>>>
parser.parse_args( '-xX' .split()) Namespace(foo=None,
x= 'X' ) |
parse_args()方法的返回值为namespace,可以用vars()内建函数化为字典:
1
2
3
4
5
|
>>>
parser = argparse.ArgumentParser() >>>
parser.add_argument( '--foo' ) >>>
args = parser.parse_args([ '--foo' , 'BAR' ]) >>>
vars(args) { 'foo' : 'BAR' } |
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('-m','--map')
parser.add_argument('-d','--dir', nargs='+')
parser.add_argument('-o','--output')
args = parser.parse_args()
mapfile = args.map
srcdir = args.dir
output = args.output
python a.py -m b.map -d c d f -o outpt.txt
参考:
https://www.cnblogs.com/linxiyue/p/3908623.html
http://blog.youkuaiyun.com/ali197294332/article/details/51180628