getopt modules 是用於命令行選項的分析器,這些選項基於 UNIX getopt() 函數組織的約定。它基本上用於分析像 sys.argv 這樣的論證序列。我們也可以理解這個模塊,因為它幫助腳本分析 sys.argv. 中的命令行參數。這個模塊的工作方式類似於 C 編程語言 getotp() 函數,用於分析命令行參數。
Python getopt 函數
這些模塊提供了一些主要功能,即 getopt()。該功能的功能是分析命令行選項和參數列表。
語法:
getopt.getopt ( args , options , [ long_options ] )
參數:
getopt.getopt()模塊採用以下參數。
參數:參數是要傳遞的參數列表
選項:選項是腳本想要識別的一串選項字母。需要參數的選項應該用冒號( :)書寫。
長選項:這是長選項名稱的字符串列表。需要參數的選項應該用等號(=)書寫。
返回類型:getopt()模塊函數的返回值由兩個元素組成。返回值的第一個元素是(選項、值)對的列表,返回值的第二個元素是選項列表被剝離時留下的程序參數的列表。
支持的選項語法包括:
- - a
- - bvalue
- - b value
- -- noargument
- -- withargument=value
- -- withargument value
Getopt()的函數參數
getopt()模塊函數接受三個參數:
- getopt()模塊的第一個參數由要分析的參數的分類組成。這通常源自 sys.argv [ 1: ](在 sys.argv [ 0 ]中忽略程序名)參數序列。
- 第二個參數是字符串,它是單字符選項的選項定義。如果任一選項需要參數,它的字母用冒號[ : ]書寫。
- getopt()模塊函數的第三個參數是長樣式選項的名稱序列。長樣式選項名稱可以由多個字符組成,例如:- noargument 或-with reguement。參數序列中的選項名稱不得包含「-」前綴。如果任何長樣式選項需要一個參數,它的名稱應該用等號(=)來簽名。
用戶可以在一次通話中組合選項的長形式和短形式。
短格式選項:
假設用戶的程序採用兩個選項- a ‘和- b ‘,其中- b ‘選項需要一個參數,那麼該值必須是” ab:”。
import getopt #importing the getopt module
print getopt.getopt ( [ ' -a ' , ' -bval ' , ' -c ' , ' val ' ] , ' ab:c: ' )
$ python getopt_short.py
( [ ( ' -a ' , ' ' ) , ( ' -b ' , ' val ' ) , ( ' -c ' , ' val ' ) ] , [ ] )
Getopt()中的長格式選項
如果用戶的程序想要採用兩個選項,例如,「- noarguement」和「-with guement」,那麼爭論的順序將是[ ‘ noarguement ‘,’ with guement = ‘]。
import getopt # importing getopt () module
print getopt.getopt ( [ ' -noarguement ' , ' -witharguement ' , ' value ' , ' -witharguement2 = another ' ] , ' ' , [ ' noarguement ' , ' witharguement = ' , ' witharguement2 = ' ] )
$ python getopt_long.py
( [ ( ' -noarguement ' , ' ' ) , ( '?witharguement ' , ' value ' ) , ( ' -witharguement2 ' , ' another ' ) ] , [ ] )
例 1:
import sys
# importing getopt module
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:
在本例中,用戶可以使用完整的形式作為「名字」和「姓氏」,而不是使用簡短的形式作為「f」和「l」。
import sys
import getopt # import getopt module
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 ( )
輸出:
用戶必須記住,短形式參數的單破折號(「-」)和長形式參數的單破折號(「-」)用戶應該使用雙破折號(「-」)。
結論:
在本文中,我們討論了 getopt() 模塊及其函數和參數。我們還解釋了不同的實現形式,並在命令行提示符中使用適當的規則,以及定義良好的示例。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/300961.html