這次介紹一下getopt這個庫。
這個庫學委在pypi-seed開源項目中使用了,本文介紹如何使用優雅的應對不同的參數,讓cli指令行程式更加彈性!
python内置庫getopt
getopt是一個簡化指令行工具參數處理的庫,可以定義短參數和長參數。這個說的比較官方。下面看看相對友好的介紹:
小白可能不太懂,它像媒人配對一樣,自動的把參數進行配對。
你告訴他參數‘-a’ 後面跟一個名字,getopt可以在程式内解析出(a,名字)這樣的映射
如果參數是這樣:
–author=雷學委 --project=hello
getopt可以幫我們處理為:
(author, “雷學委”),(project,“hello”)
getopt的調用
#getopt.getopt傳入三個參數
import getopt
getopt.getopt(args, options, [long_options])
比如pypiseed生成項目,接收了3個主要參數
name: 項目名
dir: 項目路徑
author: 作者名字
我們從pypiseed調用指令來看如何編寫getopt。
第一種 短參數類型
短參數類型,即是使用‘-‘ 加上一個單字母。比如大家非常常見的’-h’ (檢視幫助資訊) 或者 ‘-v’ (檢視版本資訊)
我們下面來看pypiseed CLI如何使用getopt子產品的。
pypiseed -p demo_project -a testuser -d /tmp
我們看到這個指令行pypiseed接受了-p , -a, -d 三個。
我們使用getopt 如何聲明處理這三個參數。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/9 10:45 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷學委
# @XueWeiTag: CodingDemo
# @File : getopstest.py
# @Project : hello
import sys
import getopt
def parse_args():
project = author = dir = None
print("argv:%s" % sys.argv)
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "p:a:d:", [])
for opt, arg in opts:
if opt in ['-p']:
project = arg
elif opt in ['-a']:
author = arg
elif opt in ['-d']:
dir = arg
print(" project:%s, author:%s, dir:%s " % (project, author, dir))
parse_args()
儲存上面代碼為getopstest.py,,輸入三個參數并運作:
-p sample -a "雷學委" -d /tmp

這裡要注意‘-’ 後面接的必須是短參數,也就是一個字母。
像‘-dir’ 這種參數會導緻getopt處了解析異常!
第二種 長參數類型
使用pypiseed生成項目的長參數類型
pypiseed --project demo_project --author testuser --dir=/tmp
上面的代碼不能支援長參數,這裡單獨做一個支援長參數的。
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/9/9 10:45 下午
# @Author : LeiXueWei
# @CSDN/Juejin/Wechat: 雷學委
# @XueWeiTag: CodingDemo
# @File : getopstest.py
# @Project : hello
import sys
import getopt
def parse_long_args():
project = author = dir = None
print("argv:%s" % sys.argv)
argv = sys.argv[1:]
opts, args = getopt.getopt(argv, "", ["project=", "author=", "dir="])
for opt, arg in opts:
if opt in ['--project']:
project = arg
elif opt in ['--author']:
author = arg
elif opt in ['--dir']:
dir = arg
print(" project:%s, author:%s, dir:%s " % (project, author, dir))
parse_long_args()
儲存上面代碼為getopstest.py,輸入三個參數并運作:
-p sample -a "雷學委" -d /tmp
這樣就會出錯:getopt.GetoptError: option -p not recognized
我們不能還是傳遞短參數,參數應該改為:
--project sample --author "雷學委" --dir "/tmp"
或者這樣也支援
--project=sample --author="雷學委" --dir="/tmp"
第三種 長短參數合并使用
這裡學委帶大家回顧上面的兩個代碼,裡面其實很像。
比較關鍵的差別的是對:getopt.getopt這個函數的調用。
#短參數解析調用
opts, args = getopt.getopt(argv, "p:a:d:", [])
#長參數解析調用
opts, args = getopt.getopt(argv, "", ["project=", "author=", "dir="])
先說說,getopt函數的參數,第一個是參數清單,它是從系統參數第二個開始到最後一個參數構成的清單。
然後第二個參數我們在第一段代碼中看到設定的是短參數。這裡定義一個字母或者多個字母即可。如果是帶參數值的,後面跟上一個冒号(:, 比如a:, 表示-a '參數值‘)
然後第三個參數在第二段代碼中是一個單詞(可以跟上‘=’符合)的清單。帶上等于符合表示,該參數後面可以跟上一個參數值。
好了,那同時處理短參數和長參數的代碼就是把第二,第三的參數位置都設定對于短參數字母串和長參數的單詞串。
參考下面代碼:
opts, args = getopt.getopt(argv, "p:a:d:", ["project=", "author=", "dir="])
總結
本文展示了getopt子產品的使用,以及實際指令行工具開發的代碼剖析。
這裡有個福利,現在讀者可以通過pypiseed,就能夠一鍵生成指令行工具項目了,運作下面代碼即可
pip install pypi-seed && pypiseed -p demo_project -a testuser -d /tmp --cli