Python中最好用的命令列引數解析工具,你知道嗎?

Python作為一種指令碼語言,可以輕鬆編寫各種工具。當你想在伺服器上執行一個工具或者服務的時候,剛需就是輸入引數(當然也可以透過配置檔案來實現)。

Python中最好用的命令列引數解析工具,你知道嗎?

如果你想在命令列上執行,你需要一個命令列引數分析模組來幫你做這個苦力。

Python中最好用的命令列引數解析工具,你知道嗎?

Python原本就提供了三個命令列引數解析模組,我在這裡列出來讓大家知道。

getopt,簡單的處理命令列引數

optparse,功能強大且易於使用,它可以輕鬆生成符合Unix/Posix規範的標準命令列指令。(Python2。7之後棄用,不會繼續發展)

argparse,更容易編寫使用者友好的命令列介面。它需要的程式定義了引數,argparse會更好的解析sys。argv,同時argparse模組還可以在使用者輸入錯誤引數時自動生成幫助和提示資訊。

大多數的初學者可能會使用getopt,它上手簡單,功能簡單。例如,optget不能解析一個引數的多個值,比如- file file1 file2 file3 3,而optparse實際上並沒有被我使用,但是考慮到在Python2。7之後不再維護,我們通常也不會使用它。

再接下來,只有工件argparse,它可以滿足我對命令解析器的幾乎所有要求。它支援解析一個引數的多個值,自動生成幫助命令和幫助文件,支援子解析器,限制引數值的範圍等等。

HelloWorld

無論學什麼,第一步都要掌握它的大致框架。在使用argparse之前,框架非常簡單,只需要記住這三行。

# mytest。pyimport argparseparser = argparse。ArgumentParser(description=“used for test”)args = parser。parse_args()

現在可嘗試

[root@localhost ~]# python mytest。py -husage: mytest。py [-h]used for testoptional arguments:  -h, ——help  show this help message and exit[root@localhost ~]# [root@localhost ~]# [root@localhost ~]# python mytest。py[root@localhost ~]#

可以使用了。

1. 入門配置

比較常用的引數配置:

除錯:debug

版本號:version

import argparseparser = argparse。ArgumentParser()parser。add_argument(‘——version’, ‘-v’, action=‘version’,                    version=‘%(prog)s version : v 0。01’,                    help=‘show the version’)parser。add_argument(‘——debug’, ‘-d’,                    action=‘store_true’,                    help=‘show the version’,                    default=False)args = parser。parse_args()print(“=== end ===”)

debug處的配置,需要講的是 action=‘store_true’ 和 default = False 的作用、區別

store_true:一旦指定了 -d 或者 ——debug ,其值就為 True,store_false則相反

default=False:未指定 -d 或者 ——debug,其值就預設為False

執行 python mytest。py -v,就會列印 version 裡的內容。

[root@localhost ~]# python mytest。py -vmytest。py version : v 0。01[root@localhost ~]#

一旦執行時,指定了引數 -v ,執行到 parser。parse_args() 就會退出程式,不會列印最後的=== end ===

2. 引數種類

引數分為 必選引數(positional arguments) 、 可選引數(optional arguments)。

在argsparse 裡怎麼實現?

必選引數

用單詞做引數,預設為必選引數

# mytest。pyimport argparseparser = argparse。ArgumentParser()parser。add_argument(“name”)args = parser。parse_args()print(args。name)

不指定name引數執行:python mytest。py

[root@localhost ~]# python mytest。py usage: mytest。py [-h] namemytest。py: error: too few arguments[root@localhost ~]#

不出所料,報告了一個錯誤,稱引數丟失。就讓我們指定:pythonmytest。pynamewangbm。

[root@localhost ~]# python mytest。py wangbmwangbm[root@localhost ~]#

可選引數

有兩種方法:

單下劃線-指定短引數,如-h;

雙下劃線-指定長引數,如- help。

# mytest。pyimport argparseparser = argparse。ArgumentParser()parser。add_argument(“-v”, “——verbosity”,                    help=“increase output verbosity”)args = parser。parse_args()if args。verbosity:    print(“verbosity turned on”)else:    print(“verbosity turned off”)

執行 python mytest。py,不會報錯。

[root@localhost ~]# python mytest。pyverbosity turned off[root@localhost ~]#

3. 引數型別

有些引數是字串,有些引數是數值。

為了有效地約束命令列中的引數,我們可以提前宣告引數的型別。Argparse將檢查引數。如果失敗,會直接丟擲錯誤。

# mytest。pyimport argparseparser = argparse。ArgumentParser()parser。add_argument(“name”)parser。add_argument(“age”, type=int)args = parser。parse_args()print(args。name)print(args。age)

測試一下

[root@localhost ~]# python mytest。py wangbm eighteenusage: mytest。py [-h] name agemytest。py: error: argument age: invalid int value: ‘eighteen’[root@localhost ~]# [root@localhost ~]# python mytest。py wangbm 18wangbm18[root@localhost ~]#

寫 eighteen 提示型別不合法,只有寫 18 才行。

4 互斥引數

有些引數是互斥的,有你沒有我。比如性別。

如何在argparse中實現?

import argparseparser = argparse。ArgumentParser()group = parser。add_mutually_exclusive_group()group。add_argument(“-m”, “——male”, action=“store_true”)group。add_argument(“-f”, “——female”, action=“store_true”)args = parser。parse_args()

如果指定了這兩個引數,將會報告錯誤。

[root@localhost ~]# python mytest。py -f[root@localhost ~]# python mytest。py -m[root@localhost ~]# python mytest。py -m -f usage: mytest。py [-h] [-m | -f]mytest。py: error: argument -f/——female: not allowed with argument -m/——male[root@localhost ~]#

5 可選值

如果是性別,可以如上放入兩個引數,然後由互斥組限制,也可以放入一個引數,在argparse限制裡,再外層判斷。

# mytest。pyimport argparseparser = argparse。ArgumentParser()parser。add_argument(“-g”, “——gender”, default=‘male’,                    choices=[‘male’, ‘female’])args = parser。parse_args()print(args。gender)

試著去執行,發現性別只能是男的或者女的,不能是“不男不女”。

[root@localhost ~]# python mytest。py ——gender malemale[root@localhost ~]# python mytest。py ——gender femalefemale[root@localhost ~]# [root@localhost ~]# [root@localhost ~]# python mytest。py ——gender otherusage: mytest。py [-h] [-g {male,female}]mytest。py: error: argument -g/——gender: invalid choice: ‘other’ (choose from ‘male’, ‘female’)[root@localhost ~]#

6. 指定檔案

通常需要在指令碼中指定配置檔案或其他檔案。可以使用下面的配置

import argparseparser = argparse。ArgumentParser()parser。add_argument(‘——file’, ‘-f’, action=‘append’,                    dest=‘files’,                    help=(‘additional yaml configuration files to use’),                    type=argparse。FileType(‘rb’))args = parser。parse_args()

dest=files,是說將命令列中,——file 的引數值賦值給變數files,你可以用args。files訪問。

action=append,由於我們會有指定多個檔案的需求,那就指定多次——file ,argparse會將其放在一個list裡。

type=argparse。FileType(‘rb’),既然是指定檔案,那麼引數應該為路徑,並指定開啟模式為rb,如果如果要取得檔案內容,可以用 args。files[0]。read()

7. 子解析器

舉個例子。

cloud-init ——debug single -name mymodule

single 後面是一個子解析器。

# cloud-init。pydef main_single(name, args):    print(“name: ”, name)    print(“args: ”, args)    print(“I am main_single”)# 新增一個子解析器subparsers = parser。add_subparsers()parser_single = subparsers。add_parser(‘single’,                      help=‘run a single module’)# 對single 子解析器新增 action 函式。parser_single。set_defaults(action=(‘single’, main_single))# require=True: 命令列指定了single解析器,必須帶上——name的引數。parser_single。add_argument(“——name”, ‘-n’, action=“store”,                           help=“module name to run”,                           required=True)args = parser。parse_args()(name, functor) = args。actionif name in [“single”]:    functor(name, args)

執行命令cloud-init single -name mymodule,輸出如下

name:  singleargs:  Namespace(action=(‘single’, ), debug=False, file=None, name=‘mymodule’)I am main_single

以上,就是 argparse 的使用方法。看完點個收藏哦!