argparse是python用于解析命令行参数和选项的标准模块,用于代替已通过时的optparse模块。java
argparse模块的做用是用于解析命令行参数,python
1:import argparsedom
2:parser = argparse.ArgumentParser()ui
3:parser.add_argument()this
4:parser.parse_args()spa
逐句解释:.net
一、首先导入该模块;命令行
二、而后建立一个解析对象;code
三、而后向该对象中添加你要关注的命令行参数和选项,每个add_argument方法对应一个你要关注的参数或选项;orm
四、最后调用parse_args()方法进行解析;解析成功以后便可使用,下面简单说明一下步骤2和3。
这些参数都有默认值,当调用parser.print_help()或者运行程序时因为参数不正确(此时python解释器其实也是调用了pring_help()方法)时,会打印这些描述信息,通常只须要传递description参数,如上。
其中:
name or flags:命令行参数名或者选项,如上面的address或者-p,--port.其中命令行参数若是没给定,且没有设置defualt,则出错。可是若是是选项的话,则设置为None
nargs:命令行参数的个数,通常使用通配符表示,其中,'?'表示只用一个,'*'表示0到多个,'+'表示至少一个
default:默认值
type:参数的类型,默认是字符串string类型,还有float、int等类型
help:和ArgumentParser方法中的参数做用类似,出现的场合也一致(参数做用解释 add_argument("a", help="params means"))
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import
argparse
def parse_args():
description = usage: %prog [options] poetry-file
This is the Slow Poetry Server, blocking edition.
Run it like
this
:
python slowpoetry.py <path-to-poetry-file>
If you are in the base directory of the twisted-intro
package
,
you could run it like
this
:
python blocking-server/slowpoetry.py poetry/ecstasy.txt
to serve up John Donne's Ecstasy, which I know you want to
do
.
parser = argparse.ArgumentParser(description = description)
help = The addresses to connect.
parser.add_argument(
'addresses'
,nargs =
'*'
,help = help)
help = The filename to operate on.Default is poetry/ecstasy.txt
parser.add_argument(
'filename'
,help=help)
help = The port to listen on. Default to a random available port.
parser.add_argument(
'-p'
,--port', type=
int
, help=help)
help = The
interface
to listen on. Default is localhost.
parser.add_argument(
'--iface'
, help=help,
default
=
'localhost'
)
help = The number of seconds between sending bytes.
parser.add_argument(
'--delay'
, type=
float
, help=help,
default
=.
7
)
help = The number of bytes to send at a time.
parser.add_argument(
'--bytes'
, type=
int
, help=help,
default
=
10
)
args = parser.parse_args();
return
args
if
__name__ ==
'__main__'
:
args = parse_args()
for
address in args.addresses:
print
'The address is : %s .'
% address
print
'The filename is : %s .'
% args.filename
print
'The port is : %d.'
% args.port
print
'The interface is : %s.'
% args.iface
print
'The number of seconds between sending bytes : %f'
% args.delay
print
'The number of bytes to send at a time : %d.'
% args.bytes</path-to-poetry-file>
|
输出为:
The address is : 127.0.0.1 .
The address is : 172.16.55.67 .
The filename is : poetry/ecstasy.txt .
The port is : 10000.
The interface is : localhost.
The number of seconds between sending bytes : 1.200000
The number of bytes to send at a time : 10.
参考:https://blog.csdn.net/qq_19924321/article/details/79882713