Python 利用argparse模塊實(shí)現(xiàn)腳本命令行參數(shù)解析
study.py內(nèi)容如下
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' import argparse def argparseFunc(): ''' 基于argparse模塊實(shí)現(xiàn)命令參數(shù)解析功能 執(zhí)行示例: python study.py -i 172.19.7.236 -p 8080 -a -r python study.py --ip 172.19.7.236 --port 7077 --auth -w -v True ''' parser = argparse.ArgumentParser(description="study.py usage help document") # 添加不帶默認(rèn)值的可解析參數(shù) parser.add_argument("-i", "--ip", help="ip addr") #注意: -h、--help為內(nèi)置參數(shù),不可用 parser.add_argument("-p", "--port",help="host port") # 添加帶默認(rèn)值的可解析參數(shù)(# action = store_true 表示是如果使用了這個(gè)參數(shù),則值參數(shù)值設(shè)置為T(mén)rue # 更多action配置可參考源碼 # 需要注意的是,不能為帶默認(rèn)值參數(shù)指定參數(shù)值,會(huì)報(bào)錯(cuò),該參數(shù)值會(huì)被當(dāng)作不識(shí)別的參數(shù) parser.add_argument("-a", "--auth", help="if auth need", action="store_true") # 添加互斥參數(shù)(比如 例中的-r和-w 同時(shí)只能用一個(gè)) exclusive_group = parser.add_mutually_exclusive_group() exclusive_group.add_argument("-r","--read", help="read enabled" , action="store_true") exclusive_group.add_argument("-w","--write", help="write enabled", action="store_true") # 添加參數(shù)時(shí)不設(shè)置設(shè)置參數(shù)說(shuō)明 parser.add_argument('-v') # show verbose # 添加參數(shù)時(shí)不設(shè)置參數(shù)全名 parser.add_argument('-V', help="version") ARGS = parser.parse_args() # 獲取命令行參數(shù) print('ARGS:', ARGS) # 獲取某個(gè)參數(shù)值 if ARGS.ip: # 注意,這里的參數(shù)名,必須使用參數(shù)全稱 print("host addr is: %s" % ARGS.ip) if ARGS.port: print("host port is: : %s" % ARGS.port) if ARGS.auth: print("auth need: : %s" % ARGS.auth) if ARGS.read: print("read enabled: %s" % ARGS.read) if ARGS.write: print("write enabled: %s" % ARGS.write) argparseFunc()
運(yùn)行測(cè)試
python study.py -i 172.19.7.236 -p 8080 -a -r python study.py --ip 172.19.7.236 --port 7077 --auth -w -v True
結(jié)果如下
python study.py -i127.0.0.1 # 注意,參數(shù)和參數(shù)值之間可以沒(méi)有空格
結(jié)果如下
python study.py -notExists 1
結(jié)果如下
如上,以上代碼實(shí)現(xiàn)是針對(duì)單個(gè)模塊腳本,如果要在多個(gè)模塊中使用咋辦?解決方法為封裝為類,具體參見(jiàn)“代碼實(shí)踐2”
#代碼實(shí)踐2
argument_parser.py #!/usr/bin/env python # -*- coding:utf-8 -*- ''' @Author : shouke ''' import argparse class ArgParser(object): ''' 參數(shù)解析器 ''' def __init__(self, none_exclusive_arguments, exclusive_arguments, description=''): self.parser = argparse.ArgumentParser(description=description) self.add_none_exclusive_arguments(none_exclusive_arguments) self.add_exclusive_arguments(exclusive_arguments) def add_none_exclusive_arguments(self, options:list): ''' 添加常規(guī)選項(xiàng)(非互斥選項(xiàng)) :param options 格式為list類型,形如 [ '"-a", "--all", help="do not ignore entries starting with ."', '"-b", "--block", help="scale sizes by SIZE before printing them"', '"-C", "--color", help="colorize the output; WHEN can be 'never', 'auto'"', '"-flag", help="make flag", action="store_true"', # action="store_true" 表示如果不設(shè)置該選項(xiàng)的值,則默認(rèn)值為true,類似的action="store_false" 表示默認(rèn)值為false ] 其中,每個(gè)list元素為argparse.ArgumentParserlei add_argument類函數(shù)實(shí)參的字符串表示,add_argument函數(shù)定義add_argument(self, *args,**kwargs) ''' for option in options: eval('self.parser.add_argument(%s)' % option) def add_exclusive_arguments(self, options:list): ''' 添加互斥選項(xiàng) :param options 格式為list,形如以下 [ ('"-r","--read",help="Read Action",action="store_true"', '"-w","--write",help="Write Action",action="store_true"') ] ''' for option_tuple in options: exptypegroup = self.parser.add_mutually_exclusive_group() for item in option_tuple: eval('exptypegroup.add_argument(%s)' % item) @property def args(self): return self.parser.parse_args()
在xxx.py中引用(注意:為了讓參數(shù)解析器起到應(yīng)起的作用,建議在腳本最上方構(gòu)造參數(shù)解析器對(duì)象)
study.py內(nèi)容如下
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'shouke' from argument_parser import ArgParser none_exclusive_arguments = [ '"-ip", help="自動(dòng)化測(cè)試服務(wù)平臺(tái)地址"', '"-projectId", help="自動(dòng)化測(cè)試項(xiàng)目id"', '"-runEnv", help="自動(dòng)化測(cè)試項(xiàng)目運(yùn)行環(huán)境"', '"-logLevel", help="日志級(jí)別"', '"-masterHost", help="master服務(wù)地址"', '"-masterPort", help="master服務(wù)端口"' ] exclusive_arguments = [ ('"-r", "--read", help="Read Action",action="store_true"', '"-w", "--write", help="Write Action",action="store_true"') ] args = ArgParser(none_exclusive_arguments, exclusive_arguments).args print(args) print(args.ip) print(args.read)
運(yùn)行測(cè)試
python study.py -i 127.0.0.1 -r
運(yùn)行結(jié)果如下
到此這篇關(guān)于Python 利用argparse模塊實(shí)現(xiàn)腳本命令行參數(shù)解析的文章就介紹到這了,更多相關(guān)Python 實(shí)現(xiàn)腳本命令行參數(shù)解析內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Pyqt5 實(shí)現(xiàn)跳轉(zhuǎn)界面并關(guān)閉當(dāng)前界面的方法
今天小編就為大家分享一篇Pyqt5 實(shí)現(xiàn)跳轉(zhuǎn)界面并關(guān)閉當(dāng)前界面的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-06-06IntelliJ IDEA安裝運(yùn)行python插件方法
在本篇文章里我們給大家分享關(guān)于IntelliJ IDEA安裝運(yùn)行python插件方法,對(duì)此有需求的讀者們可以跟著步驟學(xué)習(xí)下2018-12-12Python英文文章詞頻統(tǒng)計(jì)(14份劍橋真題詞頻統(tǒng)計(jì))
這篇文章主要介紹了Python英文文章詞頻統(tǒng)計(jì)(14份劍橋真題詞頻統(tǒng)計(jì)),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-10-10python matplotlib實(shí)現(xiàn)將圖例放在圖外
這篇文章主要介紹了python matplotlib實(shí)現(xiàn)將圖例放在圖外,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-04-04python實(shí)現(xiàn)簡(jiǎn)單socket通信的方法
這篇文章主要介紹了python實(shí)現(xiàn)簡(jiǎn)單socket通信的方法,結(jié)合實(shí)例形式分析了socket通信服務(wù)端與客戶端的具體實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-04-04如何使用virtualenv管理python環(huán)境
這篇文章主要介紹了如何使用virtualenv管理python環(huán)境,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧2024-01-01Python?Flask實(shí)現(xiàn)圖片上傳與下載的示例詳解
這篇文章主要為大家詳細(xì)介紹了如何利用Python和Flask實(shí)現(xiàn)圖片上傳與下載(支持漂亮的拖拽上傳),文中示例代碼講解詳細(xì),感興趣的可以了解一下2022-05-05