起初,最先接触python命令行传参是sys模块的argv方法,此方法功能简单,稍微增加一些需求,就不难满足需要了
那么今天就和大家聊聊optparse模块来替换sys模块的argv方法
一、optparse官方概述
1
2
3
4
5
|
optparse
is
a more convenient, flexible,
and
powerful library
for
parsing command
-
line options than
the old getopt module. optparse uses a more declarative style of command
-
line parsing: you create
an instance of OptionParser, populate it with options,
and
parse the command line. optparse
allows users to specify options
in
the conventional GNU
/
POSIX syntax,
and
additionally generates
usage
and
help
messages
for
you.
|
1
2
3
|
optparse是更加方便,灵活,和用于解析命令行选项比老Getopt模块强大。
optparse使用陈述式的命令行解析:你创建optionparser实例,选择填充它,并解析命令行。
optparse允许用户指定在传统的GNU
/
POSIX语法选项,并生成使用和帮助给你的留言。
|
二、optparser语法
1. Here’s an example of using optparse in a simple script:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
从optparse模块中导入OptionParse类
from
optparse
import
OptionParser
[...]
实例化一个OptionParse对象
parser
=
OptionParser()
调用add_ooption方法并声明参数结构
parser.add_option(
"-f"
,
"--file"
, dest
=
"filename"
,
help
=
"write report to FILE"
, metavar
=
"FILE"
)
parser.add_option(
"-q"
,
"--quiet"
,
action
=
"store_false"
, dest
=
"verbose"
, default
=
True
,
help
=
"don't print status messages to stdout"
)
调用parse_args解析参数,返回(option,args)元组
(options, args)
=
parser.parse_args()
parser.parse_args()返回值为两个
options为字典,而args为列表
|
2.帮助信息展示
-
测试optparse脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
|
[root@python script]
# cat 04_optparse.py
#!/usr/bin/env python
from
optparse
import
OptionParser
parser
=
OptionParser()
parser.add_option(
"-f"
,
"--file"
, dest
=
"filename"
,
help
=
"write report to FILE"
, metavar
=
"FILE"
)
parser.add_option(
"-q"
,
"--quiet"
,
action
=
"store_false"
, dest
=
"verbose"
, default
=
True
,
help
=
"don't print status messages to stdout"
)
(options, args)
=
parser.parse_args()
|
-
执行脚本,获取帮助信息
1
2
3
4
5
6
7
|
[root@python script]
# python 04_optparse.py -h
Usage:
04_optparse
.py [options]
Options:
-
h,
-
-
help
show this
help
message
and
exit
-
f
FILE
,
-
-
file
=
FILE
write report to
FILE
-
q,
-
-
quiet don't
print
status messages to stdout
|
3.参数解析
parser.add_option()参数说明:
-
"-f", "--file":长短选项
-
action="store":存储方式
1
2
3
4
|
存储方式有三种:store,store_false,store_true
action
=
"store"
默认值,将命令行选项后面的值(示例中
-
F
2
)和dest的值(from_step)组成字典({
'from_step'
:
2
})并赋值给options,所以options.from_step的值为
2
action
=
"store_true"
,options.from_step的值是Ture,不是
2
action
=
"store_false"
,options.from_step的值是
False
,不是
2
|
-
type="string":参数类型
-
dest="filename":存储的变量,即生成字典的key
-
default:设置参数的默认值
-
help:帮助信息
-
metavar:帮助信息中用到
4.详解参数action存储方式
起初我在学习optparse的时候,参数中的存储方式action我一个没有弄明白,为了让大家更清晰的弄清楚,我在这里写个简单的脚本做个测试。
-
情况1:action='store'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
[root@python script]
# vim 07_optparse.py
#!/usr/bin/env python
from
optparse
import
OptionParser
def
opt():
parser
=
OptionParser()
parser.add_option(
'-l'
,
'--local'
,
dest
=
'local'
,
action
=
'store'
,
help
=
'local file or directory'
)
options, args
=
parser.parse_args()
return
options, args
if
__name__
=
=
'__main__'
:
options, args
=
opt()
print
options
print
args
|
-
执行此脚本:
1
2
3
|
[root@python script]
# python 07_optparse.py
{
'local'
:
None
}
[]
|
1
2
3
4
5
6
7
|
[root@python script]
# python 07_optparse.py -h
Usage:
07_optparse
.py [options]
Options:
-
h,
-
-
help
show this
help
message
and
exit
-
l LOCAL,
-
-
local
=
LOCAL
local
file
or
directory
|
1
2
3
|
[root@python script]
# python 07_optparse.py -l nihao
{
'local'
:
'nihao'
}
[]
|
-
情况2:action='store_true'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@python script]
# cat 07_optparse.py
#!/usr/bin/env python
from
optparse
import
OptionParser
def
opt():
parser
=
OptionParser()
parser.add_option(
'-l'
,
'--local'
,
dest
=
'local'
,
action
=
'store_true'
,
help
=
'local file or directory'
)
options, args
=
parser.parse_args()
return
options, args
if
__name__
=
=
'__main__'
:
options, args
=
opt()
print
options
print
args
|
-
执行此脚本:
1
2
3
|
[root@python script]
# python 07_optparse.py
{
'local'
:
None
}
[]
|
1
2
3
4
5
6
|
[root@python script]
# python 07_optparse.py -h
Usage:
07_optparse
.py [options]
Options:
-
h,
-
-
help
show this
help
message
and
exit
-
l,
-
-
local local
file
or
directory
|
1
2
3
|
[root@python script]
# python 07_optparse.py -l nihao
{
'local'
:
True
}
[
'nihao'
]
|
-
情况3:action='store_false'
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
[root@python script]
# cat 07_optparse.py
#!/usr/bin/env python
from
optparse
import
OptionParser
def
opt():
parser
=
OptionParser()
parser.add_option(
'-l'
,
'--local'
,
dest
=
'local'
,
action
=
'store_false'
,
help
=
'local file or directory'
)
options, args
=
parser.parse_args()
return
options, args
if
__name__
=
=
'__main__'
:
options, args
=
opt()
print
options
print
args
|
-
执行此脚本:
1
2
3
|
[root@python script]
# python 07_optparse.py
{
'local'
:
None
}
[]
|
1
2
3
|
[root@python script]
# python 07_optparse.py h
{
'local'
:
None
}
[
'h'
]
|
1
2
3
|
[root@python script]
# python 07_optparse.py -l nihao
{
'local'
:
False
}
[
'nihao'
]
|
-
简论:参数值为store会把你传入的参数作为字典的value,反而store_true和store_false不会。
四、解决上篇博客的问题
-
脚本的功能:
-
显示更多丰富的帮助信息
-
批量上传单个文件到远程主机
-
批量上传多个文件到远程主机
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
#!/usr/bin/env python
#coding:utf8
from
multiprocessing
import
Process
from
optparse
import
OptionParser
import
paramiko
import
sys
import
os
Username
=
'root'
Password
=
'redhat'
Port
=
22
def
opt():
parser
=
OptionParser()
parser.add_option(
'-l'
,
'--local'
,
dest
=
'local'
,
action
=
'store'
,
help
=
"local directory's file"
)
parser.add_option(
'-r'
,
'--remote'
,
dest
=
'remote'
,
action
=
'store'
,
help
=
"remote directory's file"
)
options, args
=
parser.parse_args()
return
options, args
def
fdir(ff):
fileList
=
[]
for
p, d, f
in
os.walk(ff):
files
=
f
break
for
i
in
files:
ii
=
os.path.join(ff,i)
fileList.append(ii)
return
fileList
def
delgen(path):
try
:
if
path[
-
1
]
=
=
'/'
:
path
=
path[:
-
1
]
else
:
path
=
path
except
:
sys.exit(
1
)
return
path
def
sftpPut(ip,localDir,rfile):
try
:
s
=
paramiko.Transport((ip,Port))
s.connect(username
=
Username,password
=
Password)
sftp
=
paramiko.SFTPClient.from_transport(s)
sftp.put(localDir,rfile)
s.close()
print
'%s put successful.'
%
ip
except
:
print
'%s not exists.'
%
ip
def
sftpPuts(ip,localDir,remoteDir):
try
:
s
=
paramiko.Transport((ip,Port))
s.connect(username
=
Username,password
=
Password)
sftp
=
paramiko.SFTPClient.from_transport(s)
for
localFile
in
localDir:
filebasename
=
os.path.basename(localFile)
remoteFile
=
'%s/%s'
%
(remoteDir,filebasename)
sftp.put(localFile,remoteFile)
s.close()
print
'%s put successful.'
%
ip
except
:
print
'%s not exists.'
%
ip
def
ipProcess01(localFile,remoteFile):
for
i
in
range
(
2
,
255
):
ip
=
'192.168.0.%s'
%
i
p
=
Process(target
=
sftpPuts,args
=
(ip,localFile,remoteFile))
p.start()
def
ipProcess02(localDir,rfile):
for
i
in
range
(
2
,
255
):
ip
=
'192.168.0.%s'
%
i
p
=
Process(target
=
sftpPut,args
=
(ip,localDir,rfile))
p.start()
if
__name__
=
=
'__main__'
:
options, args
=
opt()
localDir,remoteDir
=
options.local,options.remote
try
:
if
os.path.isdir(localDir):
fileList
=
fdir(localDir)
remoteDir
=
delgen(remoteDir)
ipProcess01(fileList,remoteDir)
elif
os.path.isfile(localDir):
lfile
=
os.path.basename(localDir)
remoteDir
=
delgen(remoteDir)
rfile
=
'%s/%s'
%
(remoteDir,lfile)
ipProcess02(localDir,rfile)
except
:
print
'Usage: python %s'
%
sys.argv[
0
]
sys.exit(
1
)
|
-
脚本的帮助信息
1
2
|
[root@python script]
# python 01_optparse_process.py
Usage:python
01_optparse_process
.py
|
1
2
3
4
5
6
7
8
9
|
[root@python script]
# python 01_optparse_process.py -h
Usage:
01_optparse_process
.py [options]
Options:
-
h,
-
-
help
show this
help
message
and
exit
-
l LOCAL,
-
-
local
=
LOCAL
local directory's
file
-
r REMOTE,
-
-
remote
=
REMOTE
remote directory's
file
|
-
上传单个文件到远程服务器
1
2
3
4
|
# python 01_optparse_process.py -l /path/to/somefile -r /root/
假设,这里有一个需求,将本地
/
tmp
/
sync.sh这个shell脚本批量上传到远程主机的
/
tmp目录下:
# python 01_optparse_process.py -l /tmp/sync.sh -r /tmp
|
-
上传多个文件(指定目录下所有文件不包括子目录)到远程服务器
1
2
3
4
|
# python 01_optparse_process.py -l /path/to/directory -r /tmp/
假设,这里有一个需求,将本地某一个备份数据库目录下的所有备份文件(不包括子目录)
/
bakckup
/
mysql上传到远程主机的
/
tmp目录下:
# python 01_optparse_process.py -l /backup/mysql -r /tmp/
|
-
在实际应用当中,我们可能并不是直接的这么来用,我们可以针对主机根据应用的不同进行分组,然后可以针对某台主机进行上传,也可以针对某一个组进行上传,这样用起来会更舒服,更人性化。所谓事情都是一步步来,后面的章节中会有所介绍。
-
今天和大家就先聊到这里,我们下篇博客见。
-
如果大家对批量管理主机的实现感兴趣的可以参考我的另外一篇章:http://467754239.blog.51cto.com/4878013/1619166