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
本文轉自zys467754239 51CTO博客,原文鏈接:http://blog.51cto.com/467754239/1619323,如需轉載請自行聯系原作者
總結
以上是生活随笔為你收集整理的Python [9] optparse模块生成命令行帮助信息的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: STM32(Cortex-M3)开发,R
- 下一篇: .Net Discovery系列之十二-