在编程语言中我们经常需要从命令行读取参数,解析参数的方式多种多样。
第一种:直接给定
这种方法虽然实现起来方便,但是灵活性非常差,每次都需要打开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=
'-+'
|