命令行參數和解析輸入參數是編程和開發的重要方面。命令行參數只不過是系統命令行中程序名稱後面指定的參數。當我們在這些命令行參數中傳遞值時,這些值會直接傳遞到程序的參數中,這就是參數或變量的值存儲在程序內存中的方式。命令行參數是在系統的命令提示符 Shell 中程序名稱之後給出的,為此我們傳遞了這些參數。
所有這些參數都在程序的 main()
函數內部傳遞,通常只包含以下兩個參數:
- 程序中應該傳遞的參數數量
- 程序中傳遞的命令行參數列表
這兩類參數在 main()
函數中使用,第二類參數取自命令行參數。解析一個參數意味着我們傳遞的命令行參數在程序中是如何處理的。此外,我們在命令提示符 shell 中傳遞的所有命令行參數只由程序的 main()
函數處理。當我們必須傳遞動態數據時,當一次傳遞多個值時,這些命令行參數非常有用。當在單個命令行調用中傳遞多個參數時,這些值將根據變量和函數的數據類型和功能分配給程序的相應變量。這使得我們可以輕鬆地同時傳遞多個值,甚至不必將所有值都賦給它們特定的變量和函數。
所有編程語言都為命令行參數和解析這些參數提供了不同類型的函數,但是專門討論 Python 為我們提供了許多內置函數和多個包來執行這些任務。一個這樣的 Python 包是 Python 的 Optparse 模塊,我們可以使用它來設置命令行參數,並使用 Python 程序解析這些參數。這就是為什麼我們將在本教程中學習 Python optparse 模塊,並且我們將傳遞命令行參數&使用該模塊的函數解析它們。
Python 中的 Optparse 模塊介紹
Python 的 optparse 模塊是一個非常好的替代 getopt 包的選項,它已經成為一個現代的替代選項來處理和解析 Python 程序中的命令行參數。該模塊用於傳遞命令行參數,並使用該模塊的功能在 Python 程序中解析這些參數。Optparse 模塊是 getopt 包的一個很好的選擇,因為許多以前在 getopt 包中沒有的功能現在都可以在這個模塊中使用。許多功能,如自動幫助生成、選項回調和類型轉換,以前在 getopt 包中不可用,但現在這些選項在 optparse 模塊中對我們可用。這就是為什麼 optparse 模塊比 getopt 包更受歡迎,更適合解析命令行參數。除了 getopt 包中以前沒有的功能之外,optparse 模塊還引入了許多新功能。在本教程中,我們將只討論本模塊的一些基本功能和特性。在本教程中,我們將使用一些示例程序來演示 optparse 模塊的一些基本功能。
Python 的優化模塊:優勢
下面是 Python 的 optparse 模塊相對於其他包的一些優勢:
- optparse 模塊使我們可以非常容易地使用命令行參數,並通過 Python 程序解析它們。
- 這個模塊擁有 Python getopt 包中以前缺少的所有特性。
- optparse 模塊使我們能夠輕鬆處理動態輸入數據,它還提供了根據動態輸入數據更改輸出的選項。
- 除此之外,它還為我們提供了一些非常新的特性,有助於順利處理所有命令行參數。
這些是使用 Python 的 optparse 模塊的一些常見優勢,我們可以從這些優勢中得到一個想法,即為什麼這個模塊在命令行參數方面非常受歡迎,並且比 Python 的所有其他包都更受歡迎。
Python 的優化模塊:安裝
optparse 模塊內置了 Python,這就是為什麼我們不需要執行任何安裝過程來使用這個模塊。通過將 optparse 模塊導入示例 Python 程序,我們可以直接開始使用該模塊。要在 Python 程序中導入該模塊,我們可以使用以下代碼行:
# Importing optparse module
import optparse
之後,我們可以在程序中使用這個模塊的功能,並使用這個模塊處理命令行參數。
使用操作分析模塊
在這一部分中,我們將討論 optparse 模塊中可用的多個函數和選項,我們可以使用它們來非常容易地解析命令行參數。我們還將在這一部分使用示例程序來更好地理解 optparse 模塊的實現。但是首先,我們將學習創建一個選項解析器對象,因為這個對象將解析為程序的 main()
函數傳遞的命令行參數。
創建選項分析器對象
我們可以通過以下兩個階段由 optparse 模塊解析命令行參數:
- 首先,我們必須在程序中創建一個 OptionParser 實例來處理命令行參數,它應該用命令行參數中給出的預期選項或值來配置和構造。
- 之後,從命令行參數中給出一系列選項或值,並在程序中進行處理。
因此,首先,我們必須在程序中創建一個 OptionParser 實例,我們可以使用 optparse 模塊的 optionparser()函數來實現這一點。我們可以創建一個 OptionParser 實例,讓 optionparser 屬性解析命令行參數,在任何 Python 程序中使用下面一行代碼:
# Importing the optparse module
import optparse as opt
# Creating an OptionParser instance
opInstance = opt.optionparser()
正如我們所看到的,我們已經將 optparse 模塊導入為 opt,之後,我們使用 optionparser()函數為 OptionParser 創建了一個實例,並將其命名為“opInstance”
一旦創建了 OptionParser 實例,程序中使用的所有 optparse 選項都會隱式添加到解析器實例中。它還為我們提供了在命令行中遇到定義的選項時我們可以做什麼的信息。OptionParser 實例還為我們提供了一些函數,通過這些函數可以將選項列表傳遞給程序中的 OptionParser 構造器。但是應該注意的是,使用 OptionParser 實例中的選項的這種形式並不常用。
定義選項
當我們在程序的 OptionParser 實例中定義選項時,我們應該記住應該一次添加一個選項。程序中定義的每個選項實例代表一組同義的命令行選項字符串。我們可以使用 add_options()函數在程序中定義選項,該函數將被隱式添加到 OptionParser 實例中。在參數的開頭,我們可以使用任何未命名的字符串參數,它們被視為選項實例名。我們可以為我們正在定義的選項創建別名,也就是說,通過簡單地為它傳遞多個名稱,我們已經定義了同一個選項的長形式和短形式。
我們有兩種方法可以用 OptionParser 在程序中創建一個選項實例。以下是我們在程序中使用 OptionParser 創建選項實例的兩種方法:
方法 1:僅給出選項參數:
在這個方法中,我們將在 add_option()參數中給出 option 參數,並使用下面一行代碼來創建選項實例:
# Creating an option instance
oiVaribale = opInstance.add_option(option)
方法 2:給出字符串和值參數:
在這個方法中,我們將在定義 options 實例時,在函數的 attribute 選項中給出值參數,在 add_option()中給出可選字符串。我們可以使用下面一行代碼通過這個方法來定義選項實例:
# Creating an option instance
oiVaribale = opInstance.add_option(*opt_str, attr = userValue, ...)
在這兩種方法中,我們可以使用長形式和短形式的已定義選項實例。
如果我們只想為短選項字符串和長選項字符串定義選項,那麼我們必須使用兩種不同的方法(一種用於短選項字符串,另一種用於長選項字符串)。因此,通過這兩種方法定義的選項將只接受短選項字符串值或長選項字符串值,這取決於我們用來定義選項的函數。以下是我們可以用來定義短選項字符串或長選項字符串的兩個函數:
1)僅為長選項字符串定義選項:
我們可以使用下面的方法和 add_option()函數來為長選項字符串值定義一個選項:
# Option instance for long option string
losInstance = opInstance.add_option("--foo", attr = userValue, ...)
如我們所見,我們必須在 add_option()函數中的可選參數位置給出“- foo”值,為長選項字符串定義一個選項實例。
2)為短選項字符串定義選項實例:
我們可以使用下面一行帶有 add_option()函數的代碼來定義短選項字符串值的選項實例:
# An option instance for short option string value
sosVariable = opInstance.add_option("-f", attr = userValue, ...)
如我們所見,我們必須在 add_option()函數中給出“-f”參數來代替可選參數,從而為短選項字符串定義一個選項實例。
這就是我們如何專門為長選項字符串或短選項字符串定義一個選項實例,根據我們使用的方法,這些選項實例產生的輸出只能是長字符串或短字符串形式。
選項實例的標準操作:
我們在程序中用 OptionParser 構造器定義的選項實例有一些標準的動作選項。這些標準選項操作用於執行幾個功能,並在其中存儲特定類型的輸入值。根據程序的功能和預期的輸出,我們可以使用這些選項操作來設置我們希望在這些選項實例中存儲哪種類型的值。以下是選項實例可用的標準選項操作:
- “追加”:該動作用於將該選項實例的選項參數追加到列表中
- “store”:“store”動作用於存儲選項實例的選項參數,在 add_option()函數中默認設置
- “store _ false”:此選項用於在選項實例中存儲 false 參數
- “store _ true”:此選項用於在選項實例中存儲 true 參數
- “append_const”:在選項實例中使用“append _ const”操作,將一個常量值從選項實例追加到列表中
- “store _ const”:該選項在選項實例中用於在實例中存儲一個常量值
這些是標準的選項操作,適用於使用 add_option 函數和 optionparser 構造器定義的所有選項實例。我們可以使用其中的一個或多個來設置在解析命令行參數時存儲或/和追加哪個值。
標準選項屬性:
我們定義的選項實例也有幾個屬性來定義程序中這些選項實例的功能和工作。在解析輸入命令或執行程序中的某些特定功能時,這些屬性用作獲取某些特定參數的值。
以下是我們使用 add_option()函數定義的選項實例的標準選項屬性:
- optionInstance.default: 在命令行上看不到該選項實例時,選項實例中與該屬性一起使用的值用於該選項實例的目標
- optionInstance.dest: 它是選項實例的默認屬性,從作為輸入參數提供的選項字符串中派生而來
- 選項實例.類型:該屬性用於設置該選項實例取值的數據類型,默認設置為“字符串”
- optionInstance.action: 該屬性在選項實例中用於設置將對選項實例中給定的值執行什麼操作,默認情況下,該屬性設置為“存儲”操作
我們可以使用選項實例可用的這些屬性來設置這些選項實例將採用哪些數據類型值,以及在程序中將對這些值執行哪些操作。
Python 中的 Optparse 模塊:實現
在這一部分中,我們將通過一些解析命令行參數的示例程序來理解 Python 的 optparse 模塊的實現。我們將通過執行多個功能來理解這個模塊的實現,例如在命令行參數中獲取輸入值,使用這個模塊的類和函數。我們將通過這些示例程序產生的輸出和對它們的解釋來理解它們的工作。
看下面的示例程序,了解 optparse 模塊的工作原理:
實現 1:在選項實例中同時使用長選項值和短選項值:
在這個實現部分,我們將通過在一個示例程序中定義 optionparser 和 option 實例來理解它們的工作。我們將為長選項字符串和短選項字符串定義選項實例,並在從系統的命令 Shell 執行它們時逐個調用它們。請看下面的示例程序來理解 optparse 模塊的這個實現部分。
示例 1: 看看下面的 Python 程序,其中我們定義了長的&短的選項實例:
# Importing the optparse module
import optparse as opt
# Import the sys module
import sys
# Printing the argv value
print('ARGV value for option instances :', sys.argv[1:])
# Creating an optionparser constructor for option instances
opConst = opt.OptionParser()
# Defining an option instance with both short & long instance
opConst.add_option('-s', '--long',
dest = "output_filename",
default = "default.out",
)
# Creating another option instances with several arguments
opConst.add_option('-v', '--verbose',
dest = "verbose",
default = False,
action = "store_true",
)
opConst.add_option('--version',
dest = "version",
default = 1.0,
type = "float",
)
# Creating parser arguments for options and remainder instances
oInstance, rInstance = opConst.parse_args()
# Printing values in the output
print('VERSION of the input string :', oInstance.version)
print('VERBOSE for the input value :', oInstance.verbose)
print('OUTPUT with respect to input string :', oInstance.output_filename)
print('REMAINING for remainder is the function :', rInstance)
輸出:
While calling with the short option string argument:
C:\Users\Manish\Downloads>python code.py -s sample3.txt
ARGV value for option instances : ['-s', 'sample3.txt']
VERSION of the input string : 1.0
VERBOSE for the input value : False
OUTPUT with respect to input string : sample3.txt
REMAINING for remainder is the function : []
While calling with the long option string argument:
python code.py --long sample4.txt
ARGV value for option instances : ['--long', 'sample4.txt']
VERSION of the input string : 1.0
VERBOSE for the input value : False
OUTPUT with respect to input string : sample4.txt
REMAINING for remainder is the function : []
While calling with a custom argument for the option instance:
python code.py --lon sample4.txt
ARGV value for option instances : ['--lon', 'sample4.txt']
VERSION of the input string : 1.0
VERBOSE for the input value : False
OUTPUT with respect to input string : sample4.txt
REMAINING for remainder is the function : []
如我們所見,我們在函數中使用 long 或 short 關鍵字參數調用了選項實例中的 long 選項字符串和 short 選項。我們還為選項實例提供了一個自定義參數,選項實例也用自定義參數調用,這就是它存儲這些值的方式。這就是我們如何使用 optparse 模塊的函數來創建長和短選項字符串實例。
說明:
我們首先在程序中導入了 optparse 和 sys
模塊,以使用這些模塊的功能。之後,我們在 print 語句中使用了 sys
模塊的 argv 函數來打印選項實例,它是從程序中調用的。然後,我們使用 optionparser()函數創建了 OptionParser 構造器,並將構造器變量命名為“opConst”。之後,我們使用這個變量 optionparser 構造器在程序中使用 add_opions()函數創建選項實例。然後,我們在程序中創建了三個選項實例,在這些選項實例中,我們給出了長或短的選項字符串參數來定義選項實例的類型。之後,我們使用 optparse 模塊的 parse_args()函數來解析命令行參數。最後,我們在 print 語句中使用了 optparse 模塊的這些 args 變量來打印選項實例中的一些特定信息。解析命令行參數後,我們在打印信息之前定義了信息類別。
實現 2:在選項實例中傳遞值:
在這個實現部分,我們將為我們在選項實例中定義的參數傳遞值。在程序中解析命令行參數後,我們在程序中傳遞的這些值將打印在輸出中。我們應該記住,我們傳遞的值的數據類型應該與我們在選項實例中定義的數據類型相同;否則,它將在輸出中產生錯誤。請看下面的示例程序來理解 optparse 模塊的這個實現部分。
示例 2: 看看下面的程序,我們在其中傳遞了選項實例的值:
# Importing the optparse module
import optparse as opt
# Creating an optionparser constructor for option instances
opConst = opt.OptionParser()
# Defining multiple option instances with different data types
opConst.add_option('-a', action = "store", type = "int")
opConst.add_option('-b', action = "store", type = "float")
opConst.add_option('-c', action = "store", type = "long")
opConst.add_option('-d', action = "store", type = "complex")
opConst.add_option('-s', action = "store", type = "string")
# Parsing options instance to show input given values
parsedOptions, args = opConst.parse_args()
# Printing input string values with the respective option instances
print(The int data type input value for the first option : %-16r %s' % (type(parsedOptions.a), parsedOptions.a))
print(The float data type input value for the second option : %-16r %s' % (type(parsedOptions.b), parsedOptions.b))
print(The long data type input value for the third option : %-16r %s' % (type(parsedOptions.c), parsedOptions.c))
print(The complex data type input value for the fourth option : %-16r %s' % (type(parsedOptions.d), parsedOptions.d))
print(The string data type input value for the last option : %-16r %s' % (type(parsedOptions.s), parsedOptions.s))
輸出:
code.py -a 5 -b 31.26 -c 24260000 -d 24+26j -s max
The int data type input value for the first option : <class 'int'> 5
The float data type input value for the second option : <class 'float'> 31.26
The long data type input value for the third option : <class 'int'> 24260000
The complex data type input value for the fourth option : <class 'complex'> (24+26j)
The string data type input value for the last option : <class 'str'> max
如我們所見,在給出不同數據類型的輸入值後,這些輸入值被分配給各自的數據類型選項實例。這就是我們如何給出不同的數據類型輸入值,並使用命令行 shell 將它們解析為已定義的選項實例。
說明:
在定義了 optionparser 構造器之後,我們已經在程序中定義了多個選項實例。這些選項實例是用設置為“存儲”的操作參數來定義的,以便為這些選項實例存儲給定的輸入值。此外,這些選項實例被設置為採用不同的數據類型,以便當輸入中給出特定的數據類型值時,它將僅存儲到該特定的選項實例中。最後,我們打印輸入值,使用 print 語句中的 parsedOptions 構造器對輸入值進行解析並存儲到特定的選項實例中。我們還在結果中用值打印了值的數據類型。
注意:應該注意的是,在為選項實例提供輸入值時,如果我們提供的數據類型輸入值不同於選項實例中定義的值,將會出現錯誤,並且在輸出中會顯示錯誤消息。為了演示這一點,我們將運行 Python 代碼,並給出不同的數據類型值,而不是選項實例的數據類型。查看下面的示例程序,了解選項實例的概念:
# Importing the optparse module
import optparse as opt
# Creating an optionparser constructor for option instances
opConst = opt.OptionParser()
# Defining multiple option instances with different data types
opConst.add_option('-a', action = "store", type = "int")
# Parsing options instance to show input given values
parsedOptions, args = opConst.parse_args()
# Printing input string values with the respective option instances
print(The int data type input value for the first option : %-16r %s' % (type(parsedOptions.a), parsedOptions.a))
輸出:
code.py -a c
Usage: code.py [options]
code.py: error: option -a: invalid integer value: 'c'
如我們所見,當我們為選項實例提供不同的數據類型輸入值時,輸出中會顯示一條錯誤消息。
實現 3:解析命令行參數以打印表格:
到目前為止,我們已經理解了選項實例和 optionparser 構造器的工作和實現。現在,我們將使用 optparse 模塊及其函數根據輸入值在命令行 shell 中打印一個表。我們將在程序中使用 for
循環來循環輸入值,因此,使用 optparse 模塊的功能打印命令 Shell 中的表。這將幫助我們更好地理解使用 optparse 模塊解析命令行參數的工作和實際實現。請看下面的示例程序,其中我們在命令 Shell 中打印了表:
示例 4: 查看下面的 Python 程序,了解 optparse 模塊的實際實現:
# Importing the optparse module
import optparse as opt
# Define a function to print table of n
def tablePrint(num, destCheak):
# Using for loop to print the table
for a in range(1,11):
table = a * num
# Using if to check if destination input given is other than 0
if destCheak:
print(table)
return table
# Define main function to add options for taking input value
def Main():
# Create the OptionParser constructor
opConst = opt.OptionParser()
# Adding multiple option instances with specific functions
opConst.add_option('-m', dest = 'num',
type = 'int',
help = 'specify the nth table number to print table in the output') # Using help argument to show help message in the case of error
opConst.add_option('-c', dest = 'out',
type = 'string',
help = 'specify an output file for the input value (Optional)')
opConst.add_option("-b", "--all",
action = "store_true",
dest = "prin",
default = False,
help = "print all numbers up to N from the print table function")
# Adding parsed options constructor
(optionParsed, args) = opConst.parse_args()
if (optionParsed.num == None):
print (opConst.usage)
exit(0)
else:
number = optionParsed.num
# Calling the print table function
result = tablePrint(number, optionParsed.prin)
# Printing the last term of table in the result
print ("This is the table of given input value number with last term:" + str(result))
# Checking if given input value is not 0
if (optionParsed.out != None):
# Opening a file in append mode to print table
func = open(optionParsed.out, "a")
# Writing in the file we appended
func.write(str(result) + '\n')
# Driver code to call main function
if __name__ == '__main__':
# Calling the main function
Main()
輸出:
python code.py -m 7 -b
7
14
21
28
35
42
49
56
63
70
This is the table of given input value number with last term:70
正如我們所看到的,“7”的表,也是命令 Shell 中的輸入值,在程序中解析命令行參數後,會打印在輸出中。
這就是我們如何使用 Python 的 optparse 模塊來解析命令行參數,並通過 Python 程序使用它們。
原創文章,作者:GEJVA,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/129861.html