起初,最早接觸python命令行傳參是sys模塊的argv方法,此方法功能簡單,稍微增長一些需求,就不難知足須要了python
那麼今天就和你們聊聊optparse模塊來替換sys模塊的argv方法mysql
1、optparse官方概述sql
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.
optparse是更加方便,靈活,和用於解析命令行選項比老Getopt模塊強大。 optparse使用陳述式的命令行解析:你建立optionparser實例,選擇填充它,並解析命令行。 optparse容許用戶指定在傳統的GNU / POSIX語法選項,並生成使用和幫助給你的留言。
2、optparser語法shell
1. Here’s an example of using optparse in a simple script:數據庫
從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.幫助信息展現vim
測試optparse腳本
服務器
[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()
執行腳本,獲取幫助信息app
[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.參數解析ide
parser.add_option()參數說明:oop
"-f", "--file":長短選項
action="store":存儲方式
存儲方式有三種: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'
[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
執行此腳本:
[root@python script]# python 07_optparse.py {'local': None} []
[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
[root@python script]# python 07_optparse.py -l nihao {'local': 'nihao'} []
狀況2:action='store_true'
[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
執行此腳本:
[root@python script]# python 07_optparse.py {'local': None} []
[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
[root@python script]# python 07_optparse.py -l nihao {'local': True} ['nihao']
狀況3:action='store_false'
[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
執行此腳本:
[root@python script]# python 07_optparse.py {'local': None} []
[root@python script]# python 07_optparse.py h {'local': None} ['h']
[root@python script]# python 07_optparse.py -l nihao {'local': False} ['nihao']
簡論:參數值爲store會把你傳入的參數做爲字典的value,反而store_true和store_false不會。
4、解決上篇博客的問題
腳本的功能:
顯示更多豐富的幫助信息
批量上傳單個文件到遠程主機
批量上傳多個文件到遠程主機
#!/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)
腳本的幫助信息
[root@python script]# python 01_optparse_process.py Usage:python 01_optparse_process.py
[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
上傳單個文件到遠程服務器
# 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
上傳多個文件(指定目錄下全部文件不包括子目錄)到遠程服務器
# 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