獲取選擇模塊是一個基於 Unix 建立的約定的命令行選項解析器getopt()
函數。它通常用於解析參數序列,例如 sys.argv。換句話說,該模塊幫助腳本解析 sys.argv 中的命令行參數。它的工作原理與C類似getopt()
解析命令行參數的函數。
Python getopt 函數
該模塊提供的第一個函數具有相同的名稱,即 getopt()
。它的主要函數是解析命令行選項和參數列表。該函數的語法如下:
用法: getopt.getopt(args, options, [long_options])
參數:
args:要傳遞的參數列表。
options:腳本想要識別的選項字母字符串。需要參數的選項後麵應跟一個冒號 (:)。
long_options:具有長選項名稱的字符串列表。需要參數的選項後麵應跟一個等號 (=)。
返回類型:返回由兩個元素組成的值:第一個元素是(選項,值)對的列表。第二個是選項列表被刪除後留下的程序參數列表。
示例 1:
import sys
import getopt
def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:")
except:
print("Error")
for opt, arg in opts:
if opt in ['-f']:
first_name = arg
elif opt in ['-l']:
last_name = arg
print( first_name +" " + last_name)
full_name()
輸出:
這裏我們創建了一個函數full_name()
,它從命令行獲取名字和姓氏後打印全名。我們還將名字縮寫為‘f’,姓氏縮寫為‘l’。
示例 2:現在讓我們看一下這種情況,我們可以使用完整的形式,如‘first_name’和‘last_name’,而不是像‘f’或‘l’這樣的縮寫。下麵的代碼使用完整的形式來打印全名;
import sys
import getopt
def full_name():
first_name = None
last_name = None
argv = sys.argv[1:]
try:
opts, args = getopt.getopt(argv, "f:l:",
["first_name =",
"last_name ="])
except:
print("Error")
for opt, arg in opts:
if opt in ['-f', '--first_name']:
first_name = arg
elif opt in ['-l', '--last_name']:
last_name = arg
print( first_name +" " + last_name)
full_name()
輸出:
注意:應使用代碼中參數的短形式的單破折號(“-”)和長形式的雙破折號(“-”)。
相關用法
- Python String format()用法及代碼示例
- Python abs()用法及代碼示例
- Python any()用法及代碼示例
- Python all()用法及代碼示例
- Python ascii()用法及代碼示例
- Python bin()用法及代碼示例
- Python bool()用法及代碼示例
- Python bytearray()用法及代碼示例
- Python callable()用法及代碼示例
- Python bytes()用法及代碼示例
- Python chr()用法及代碼示例
- Python compile()用法及代碼示例
- Python classmethod()用法及代碼示例
- Python complex()用法及代碼示例
- Python delattr()用法及代碼示例
- Python dict()用法及代碼示例
- Python dir()用法及代碼示例
- Python divmod()用法及代碼示例
- Python enumerate()用法及代碼示例
- Python staticmethod()用法及代碼示例
- Python filter()用法及代碼示例
- Python eval()用法及代碼示例
- Python float()用法及代碼示例
- Python format()用法及代碼示例
- Python frozenset()用法及代碼示例
注:本文由純淨天空篩選整理自RajuKumar19大神的英文原創作品 Getopt module in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。