Python [9] optparse模块生成命令行帮助信息
起初,最先接触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
Python [9] optparse模块生成命令行帮助信息相关推荐
- 【转】Python之optparse模块OptionParser的使用方法
一.基本用法 optparse,是一个更够让程序设计人员轻松设计出简单明了.易于使用.符合标准的Unix命令例程式的Python模块.生成使用和帮助信息 首先你必须导入该类,并创建一个OptionPa ...
- Python3,3行代码,自动为脚本生成命令行,我默默的收藏了。
为python脚本生成命令行 1.引言 2.常规方法 3.Fire模块 3.1 模块介绍 3.2 代码示例 3.2.1 参数替换 3.2.2 类支持 3.2.3 代码示例 4.总结 1.引言 小屌丝: ...
- 如何使用Python脚本转换数据和命令行
在如何使用Python脚本转换数据和命令行中,我们将深入探讨如何使用Python脚本和命令行来转换数据. 但是首先,值得提出一个您可能正在思考的问题:" Python如何适合命令行,为什么当 ...
- Python中random模块生成随机数详解
Python中random模块生成随机数详解 本文给大家汇总了一下在Python中random模块中最常用的生成随机数的方法,有需要的小伙伴可以参考下 Python中的random模块用于生成随机数. ...
- 【Python】常用模块安装命令
[Python]常用模块安装命令 Python常用模块安装命令 pylab模块 No module named 'apkutils' No module named 'win32api' Python ...
- python|3种运行cmd命令行的方法
python|3种运行cmd命令行的方法 1.执行cmd命令,不显示执行过程中弹出的黑框 def run_cmd( cmd_str='', echo_print=1):""&quo ...
- python 命令行解析模块_【Python模块】命令行解析--argparse
python命令行解析 前言 当你还在使用 if len(sys.argv) > 1: 这样的方式判断选项和参数的时候,是否已意识到已经落伍了. 我在bash中用过getopt getopts, ...
- Python fire官方文档教学(自动生成命令行,个人觉得意义不大,不如argparse)
0x00 简介 欢迎来到Python Fire指南! Python Fire是一个Python库,只需对Fire进行一次调用即可将任何Python组件转变为命令行界面. 让我们开始吧! 0x01 安装 ...
- python 命令行解析模块_Python命令行解析模块详解
python2.7 怎么解析命令行输入的中文参数 本文实例讲述了python读取命令行参数的方法.分享给大家供大家参考.具体分析如下: 如果想对python脚本传参数,python中对应的argc, ...
最新文章
- windows hider
- DSP调试报错:Error connecting to the target:Connect to PRSC failed
- php 5.6 新特性,PHP5.6新特性介绍
- 策马扬鞭,踏上新征程。
- java遍历对象属性_java开发中遍历一个对象的所有属性并set值 缓存优化
- 反思走火入魔 急功近利:一步一步的做 一步一步的走 顺其自然 水到渠成
- SecureCRTPortable - 破解
- 【springboot】之 解析@EnableWebMvc 、WebMvcConfigurationSupport和WebMvcConfigurationAdapter
- PageRequestManager
- 【HDU-5963】朋友【树上博弈】
- syswow64删除文件_syswow64,小编告诉你syswow64是什么文件夹
- PC微信聊天记录备份恢复测试
- 笔记本禁用键盘的方法(已试过win10/win11均可生效)
- SAP MM移动平均价和标准价逻辑
- python创建函数内部静态变量
- 四个有关文件传输的CTF WEB题(深育杯FakeWget、极客大挑战where_is_my_FUMO、2021陇原战疫CheckIN、N1CTF-curl trick)
- 于博士Cadence教程内容目录
- ubunutu个人配置
- 【模电实验】电压比较器
- 【深度学习笔记】神经网络模型及经典算法知识点问答巩固(算法工程师面试笔试)