【Python 命令行參數解析: optparse 模塊】
阿新 • • 發佈:2018-07-02
如何實現 efault pre options weixin 分享 opts XA header
大家在使用Python進行腳本開發時,經常需要通過終端交互的方式對Python的腳本模塊進行調用。這時在
Python模塊中提供基礎的命令行參數支持是必不可少的。那麽,在Python中我們如何實現命令行參數的傳入和解析呢,如下內容將對此進行簡要的介紹。
Python對命令行參數解析的支持
Python中通過兩個內建模塊對命令行參數解析進行支持:getopt 和 optparse
兩種內置支持
模塊名 | 功能說明 |
---|---|
getopt | 對命令行參數進行簡單的處理 |
optparse | 能夠對命令行參數進行復雜的處理,並便捷生成類Unix的幫助信息,功能更為強大。 |
基本使用
示例代碼:
"""A simple usage example for optparse module By Fat Boy. """ from optparse import OptionParser # Import the module def main(): opts = parse_command() print("Param filename: " + opts.filename) print("Param Debug: " + str(opts.debug)) def parse_command(): parser = OptionParser() # Initialize the OptionParser class # Add commandline parameters format parser.add_option("-f", "--filename", dest="filename", help="Set the output file name") parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch") # Parse the command params (opts, args) = parser.parse_args() return opts if __name__ == "__main__": main()
測試
在終端中輸入如下命令,執行argv.py。
python argv.py --file=outfile -D
查看輸出結果:
Param filename: outfile
Param Debug: True
關鍵方法介紹
基於 "optparse" 模塊處理命令行參數時, "add_option()" 是最為重要的方法
OptionParser 初始化
add_option()定義命令行參數
parser.add_option("-D", "--Debug", action="store_true", dest="debug", default=False, help="Set the debug switch")
參數名稱 | 功能 | 說明 |
---|---|---|
參數0 | 第一個參數,命令行參數短名稱 | 參考代碼:“-D” |
參數1 | 第二個參數,命令行參數長名稱 | 參考代碼: "--Debug" |
action | 指示 optparse 當解析到一個命令行參數時該如何處理store、store_true、store_false、store_const 、append 、count 、callback | 默認為store |
dest | 設置存儲參數值的變量名 | 存儲的內容就是參數後面緊挨的內容 |
type | 設置參數的數據類型 | 默認為string,還可設置:int/float |
default | 設置參數的默認值 | |
help | 設置參數的幫助說明文字 | |
metavar | 用於提醒用戶參數應輸入的值 | 顯示為大寫 |
說明
- action參數的取值默認為 store,表示把該命令行參數存儲的options對象中。
- store_true 和 store_false 一般用於只有命令沒有值的情況。store_true 表示當該命令在命令行中出現時,將 dest 屬性所定義的變量值設置為 true。 相應的, store_false 則表示當該命令在命令行中出現時,將 dest 屬性所定義的變量值設置為 false.
parse_args()
該方法返回解析後的命令行參數值,使用如下面所示:
(opts, args) = parser.parse_args()
用戶可以通過opts.[dest指定的變量名] 來獲得解析後的參數。
更多內容請關註衛星公眾號
【Python 命令行參數解析: optparse 模塊】