Python3 中g(shù)etopt用法

getopt

該模塊是專門用來處理命令行參數(shù)的。
函數(shù):opts, args = getopt(args, shortopts, longopts = [])
參數(shù):

  • args: 一般是sys.argv[1:]
  • shortopts: 短格式 (-) , 只表示開關(guān)狀態(tài)時(shí),即后面不帶附加數(shù)值時(shí),在分析串中寫入選項(xiàng)字符。當(dāng)選項(xiàng)后面要帶一個(gè)附加數(shù)值時(shí),在分析串中寫入選項(xiàng)字符同時(shí)后面加一個(gè):號 , 如"vc:"。
  • longopts:長格式(--) , 只表示開關(guān)狀態(tài)時(shí),即后面不帶附加數(shù)值時(shí),在隊(duì)列中寫入選項(xiàng)字符。當(dāng)選項(xiàng)后面要帶一個(gè)附加數(shù)值時(shí),在隊(duì)列中寫入選項(xiàng)字符同時(shí)后面加一個(gè)=號 , 如["help", "log="] 。

返回:

  • opts: 分析出的格式信息,是一個(gè)兩元組的列表,即[(選項(xiàng)串1, 附加參數(shù)1), (選項(xiàng)串2, '')], 注意如果沒有附加數(shù)值則為空字符串
  • args: 為不屬于格式信息的剩余的命令行參數(shù)
import sys
import getopt


if __name__ == '__main__':
    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hi:', ['help', 'input='])
        print (opts, args)
    except getopt.GetoptError as e:
        print ('Got a eror and exit, error is %s' % str(e))

測試結(jié)果如下:

  • 不傳任何參數(shù), 返回兩個(gè)空的list
$ python getopt_test.py
[] []
  • 不傳帶---的參數(shù), opts是空的列表,args是兩個(gè)入?yún)⒌牧斜?/li>
$ python getopt_test.py value1 value2
[] ['value1', 'value2']
  • 輸入含有-h的參數(shù), 可以得知h后不接:, 表明-h不會去取值
$ python getopt_test.py -h
[('-h', '')] []
$ python getopt_test.py -h 1
[('-h', '')] ['1']
$ python getopt_test.py -h -p
Got a eror and exit, error is option -p not recognized
  • 輸入含有-i的參數(shù), 可以得知i后接:, 表明-i一定會去取值
$ python getopt_test.py -i
Got a eror and exit, error is option -i requires argument
$ python getopt_test.py -i 1
[('-i', '1')] []
$ python getopt_test.py -i -p
[('-i', '-p')] []
  • 輸入其他帶有-的參數(shù), 會直接報(bào)錯,不認(rèn)識這個(gè)參數(shù)
$ python getopt_test.py -a
Got a eror and exit, error is option -a not recognized
  • 輸入帶有--的參數(shù), 和帶-的參數(shù)類似, 如果后面不接=,則表示不需要取值, 后面接了=, 則表示一定要取值。
$ python getopt_test.py --help
[('--help', '')] []

$ python getopt_test.py --help 1
[('--help', '')] ['1']

$ python getopt_test.py --help --ls
Got a eror and exit, error is option --ls not recognized

$ python getopt_test.py --help --input
Got a eror and exit, error is option --input requires argument

$ python getopt_test.py --help --input 2
[('--help', ''), ('--input', '2')] []

$ python getopt_test.py --help --input 2 3
[('--help', ''), ('--input', '2')] ['3']
  • 輸入全體參數(shù)
$ python getopt_test.py -h -i 1 --help --input 2 3
[('-h', ''), ('-i', '1'), ('--help', ''), ('--input', '2')] ['3']
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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