筆記帶有個人側重點,不追求面面俱到。
1 命令行參數(shù)
出處: 菜鳥教程 - Python3 命令行參數(shù)
1.1 基礎用法
Python 中可以所用 sys
的 sys.argv
來獲取命令行參數(shù):
注意:
sys.argv[0]
為腳本名。
實例:
test.py 文件:
#!/usr/bin/python3
import sys
print ('參數(shù)個數(shù)為:', len(sys.argv), '個參數(shù)。')
print ('參數(shù)列表:', str(sys.argv))
print ('腳本名:', str(sys.argv[0]))
運行結果:
>> python test.py arg1 arg2 arg3
參數(shù)個數(shù)為: 4 個參數(shù)。
參數(shù)列表: ['test.py', 'arg1', 'arg2', 'arg3']
腳本名: test.py
1.2 getopt 模塊
getopt
模塊是專門處理命令行參數(shù)的模塊,用于獲取命令行選項和參數(shù)。該模塊提供了兩個方法及一個異常處理來解析命令行參數(shù)。
1.2.1 getopt.getopt 方法
語法:
getopt.getopt(args, shortopts, longopts=[])
參數(shù):
-
args
:要解析的命令行參數(shù)列表; -
shortopts
:接收字符串,解析為“短選項”。shortopts 后的冒號 : 表示該選項必須有附加的參數(shù),不帶冒號表示該選項不附加參數(shù); -
longopts
:接收列表,解析為“長選項”。longopts 后的等號 = 表示如果設置該選項,必須有附加的參數(shù),否則就不附加參數(shù)。
返回值:
-
opts
:由元組 (opt, value) 組成的列表。例如輸入"-h -i inputfile -o outputfile" 返回值就是 [(‘-h’, ‘’), (‘-i’, ‘inputfile’), (‘-o’, ‘outputfile’)]; -
args
:參數(shù)(value)列表,包含除了長選項和短選項以及各自選項的參數(shù)以外的其他未知的參數(shù)。
注意:
- 長選項和短選項以及各自的參數(shù)都會按先后次序放在
opts
中;- 返回的
opt
里面,-
和--
都被保留下來了;- 長選項沒有寫完的時候,會被自動補全。比如用戶輸入的是
--u
,通過 getopt 會被自動補全成--user
。
實例:
# test.py
import sys
import getopt
def site():
argv = sys.argv[1:] # 以空格分割的字符串列表
try:
opts, args = getopt.getopt(argv, "abn:u:", ["name=", "url="])# 長選項模式
except Exception as err:
print(err)
print("opts: ", opts)
print("args: ", args)
if __name__ == "__main__":
site()
輸出:
1)正常使用
>>> python test.py -a -b -u item1 -n item2 --n item3 --url item4
opts: [('-a', ''), ('-b', ''), ('-u', 'item1'), ('-n', 'item2'), ('--name', 'item3'), ('--url', 'item4')]
args: []
2)只輸入?yún)?shù)
>>> python test.py item1 item2
opts: []
args: ['item1', 'item2']
3)只輸入選項
>>> python test.py -a
opts: [('-a', '')]
args: []
>>> python test.py -n
option -n requires argument # 報錯
4)錯誤輸入選項
>>> python test.py -
opts: []
args: ['-']
>>> python test.py --
opts: []
args: []
>>> python test.py ---
option --- not recognized # 報錯
>>> python test.py -c
option -c not recognized # 報錯
>>> python test.py ---b
option ---b not recognized # 報錯
>>> python test.py -n-a
opts: [('-n', '-a')]
args: []
>>> python test.py -a-n
option -- not recognized # 報錯
>>> python test.py -a--n
option -- not recognized # 報錯
5)錯誤輸入?yún)?shù)
>>> python test.py -a item
opts: [('-a', '')]
args: ['item']
>>> python test.py -aitem
option -i not recognized # 報錯
>>> python test.py -antem
opts: [('-a', ''), ('-n', 'tem')]
args: []
>>> python test.py -abntem
opts: [('-a', ''), ('-b', ''), ('-n', 'tem')]
args: []
>>> python test.py -acntem
option -c not recognized
>>> python test.py -n item1 -a item2 --n item3
opts: [('-n', 'item1'), ('-a', '')]
args: ['item2', '--n', 'item3']
>>> python test.py -n item1 item2 -a
opts: [('-n', 'item1')]
args: ['item2', '-a']
>>> python test.py item1 item2 -a
opts: []
args: ['item1', 'item2', '-a']
總結:(歡迎指正、補充)
- 命令行參數(shù)從左到右、依次解析;
- 一般情況下以空格分割選項和參數(shù),附加參數(shù)的短選項后緊跟的參數(shù)也可以被解析,例如:
-nitem
; - 解析時,先碰到未定義的選項時,會報錯,先碰到多余的參數(shù)時,之后的參數(shù)都被放入返回值
args
中; - 短選項可以采用
-abn
的樣式輸入,無附加參數(shù)的選項必須在前,否則會報錯。
1.2.2 getopt.gnu_getopt 方法
語法:
getopt.gnu_getopt(args, shortopts, longopts=[])
此函數(shù)與 getopt() 類似,區(qū)別在于它默認使用 GNU 風格的掃描模式。這意味著選項和非選項參數(shù)可能會混在一起。getopt() 函數(shù)將在遇到非選項參數(shù)時立即停止處理選項。
如果選項字符串的第一個字符為 +
,或者如果設置了環(huán)境變量 POSIXLY_CORRECT
,則選項處理會在遇到非選項參數(shù)時立即停止。
1.2.3 Exception getopt.GetoptError
當參數(shù)列表中出現(xiàn)不可識別的選項或者當一個需要參數(shù)的選項未帶參數(shù)時將引發(fā)此異常。此異常的參數(shù)是一個指明錯誤原因的字符串
對于長選項,將一個參數(shù)傳給不需要參數(shù)的選項也將導致引發(fā)此異常。(沒發(fā)現(xiàn))
msg 和 opt 屬性會給出錯誤消息和關聯(lián)的選項;如果沒有關聯(lián)到異常的特定選項,則 opt 將為空字符串。
報錯 1:
需要參數(shù)的選項未帶參數(shù)。
報錯 2:
如果 longopts 為 [‘foo’, ‘frob’],則選項 --fo 將匹配為 --foo,但 --f 將不能得到唯一匹配,因此將引發(fā) GetoptError。
1.2.4 exception getopt.error
GetoptError 的別名,用于向后兼容。文章來源:http://www.zghlxwxcb.cn/news/detail-691862.html
擴展閱讀: 《Python 官方文檔》:getopt — C 風格的命令行選項解析器文章來源地址http://www.zghlxwxcb.cn/news/detail-691862.html
到了這里,關于菜鳥教程《Python 3 教程》筆記 EX 01:命令行參數(shù)的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網(wǎng)!