Python自定義命令行參數(shù)

用過(guò)別人的腳本命令參數(shù)后,如何自己也自定義命令行參數(shù)呢,下面教給大家這些紙老虎:

命令行模塊getopt:
getopt函數(shù)中一共有三個(gè)參數(shù):
getopt.getopt(sys.argv[1:], "ho:i:", ["help", "output="])

  • sys.argv[1:] 和C語(yǔ)言中的argv相似,我們一般寫(xiě)sys.argv[1:]來(lái)過(guò)濾第一個(gè)參數(shù),因?yàn)榈谝粋€(gè)參數(shù)是python腳本文件名,一般對(duì)我們沒(méi)有實(shí)際用處,過(guò)濾掉即可。
  • "ho:i:":剛看的同學(xué)肯定有點(diǎn)懵*,可以稱(chēng)作為短格式分析串,是否曾經(jīng)用過(guò)類(lèi)似 XXX -i XXX -o XXX這樣的命令,這對(duì)幫助你理解短格式分析串很有幫助,h不加":",表示不帶參數(shù)。即-h,o后面有":"代表需要加參數(shù)-o "your file path",那么短格式,輸入一個(gè)"-"即可。
  • ["help", "output="]:python列表形式表示,稱(chēng)為長(zhǎng)格式串,無(wú)"="不加參數(shù),帶"="需要加參數(shù)類(lèi)似短格式串。用法為--help --output "your file path"。

以上分析相信你已經(jīng)了解了這些參數(shù)作用,那么上一段簡(jiǎn)短的代碼:

if __name__ == '__main__':

# for item in allfile:
#     print item
#     print os.path.splitext(item)[0]
#getopt()
try:
options, args = getopt.getopt(sys.argv[1:], "ho:i:", ["help", "ip=", "port="])
except getopt.GetoptError:
print 'hi Sam getopt error!Please input -h or --help'
sys.exit(1)

for name, value in options:
    if name in ("-h", "--help"):
        usage()
        print ""
    elif name in("-o","-i"):
        print "short  parameter %s" % (value)
    elif name in("--ip","--port"):
        print "long  parameter %s"%(value)
    
for item in args:
    print item

python環(huán)境下我們輸入命令測(cè)試我們的腳本是否正確:

$ python getoptTest.py -o sam -i tom
short parameter sam
short parameter tom

$ python getoptTest.py --port 80
long parameter 80
python FileTest.py --port 80 -o Sam 100 120
long parameter 80
short parameter Sam
100
120

如果我們估計(jì)輸入錯(cuò)誤:
$ python FileTest.py -i

異常捕獲結(jié)果:hi Sam getopt error!Please input -h or --help

自定義就是這么簡(jiǎn)單。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容