簡介
當遇到需要參數的情況時,往往有以下三種處理方法[1]:
直接給定
這種方法實現起來方便,但是靈活性稍差,每次都需要打開源碼修改。
手動解析
這種方法也算是比較常用,但是當參數過多時就顯示出來不方便了,因爲每次輸入的格式以及參數的個數都必須一點不差。舉個簡單的小例子說明這種方法如何使用:
# python 代碼-手動解析參數
# 文件名稱test.py
import sys
if __name__ == '__main__':
print sys.argv[0]
print "end"
$python test.py 1
test.py
end
自動解析
相比上述兩種方法,這種自動解析的方法更加靈活,且參數可以選擇,順序可以不確定,因此建議使用這種方法。其主要依賴python包argparse。
接下來主要介紹python命令行解析模塊argparse***[2][3]***:
argparse
模塊使得用戶友好的命令行編程更加方便。首先定義程序中需要什麼參數,然後argparse
會自動從sys.argv
中解析之前定義的參數。
argparse
還可以自動生成幫助文檔,並且當用戶輸入錯誤的參數時自動報錯。
來個例子
# python代碼 - argparse 示例
# 代碼名稱: prog.py
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))
命令行運行如下命令可以查看幫助信息:
$ python prog.py -h
usage: prog.py [-h] [--sum] N [N ...]
Process some integers.
positional arguments:
N an integer for the accumulator
optional arguments:
-h, --help show this help message and exit
--sum sum the integers (default: find the max)
使用合適的參數運行程序,可以得到輸入參數的max或者sum,如果輸入不合適的參數,則程序會直接報錯,如下:
$ python prog.py 1 2 3 4
4
$ python prog.py 1 2 3 4 --sum
10
$ python prog.py a b c
usage: prog.py [-h] [--sum] N [N ...]
prog.py: error: argument N: invalid int value: 'a'
創建一個解釋器
>>>parser = argparse.ArgumentParser(description='Process some integers.')
ArgumentParser
對象存儲瞭解析命令行參數所需的所有信息。
添加參數
add_argument()
函數實現了將需要的參數添加到ArgumentParser
對象中。
這些調用告訴ArgumentParse
對象怎樣提取命令行中的參數,並如何將其轉化爲所需的對象。This information is stored and used when parse_args()
is called. For example:
>>>parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
>>>parser.add_argument('--sum', dest='accumulate', action='store_const',
const=sum, default=max,
help='sum the integers (default: find the max)')
調用完parse_args()
函數後會返回兩個對象,integers
和accumulate
。
integers
是一個或多個(list)int型的數;
accumulate
是一個sum()
函數(--sum
已調用),或者max()
(--sum
沒調用)
解析參數
>>> parser.parse_args(['--sum', '7', '-1', '42'])
Namespace(accumulate=<built-in function sum>, integers=[7, -1, 42])
注意: 在一個script中,parse_args()
函數一般不帶參數直接調用,而參數是直接在命令行中給出,然後ArgumentParser
會在sys.argv
中自動解析相應的參數。
ArgumentParser對象
ArgumentParser
對象定義如下:
class argparse.ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)
其每一個參數的定義如下:
-
prog - The name of the program (default: sys.argv[0])
默認情況下, ArgumentParser對象根據sys.argv[0]的值(不包括路徑名)生成幫助信息中的程序名。 -
usage - The string describing the program usage (default: generated from arguments added to parser)
默認情況下,ArgumentParser對象可以根據參數自動生成用法信息 -
description - Text to display before the argument help (default: none)
description 用於展示程序的簡要介紹信息,通常包括:這個程序可以做什麼、怎麼做。在幫助信息中 description位於用法信息與參數說明之間 -
epilog - Text to display after the argument help (default: none)
與description類似,程序的額外描述信息,位於參數說明之後 -
parents - A list of ArgumentParser objects whose arguments should also be included
有時多個解析器可能有相同的參數集,爲了實現代碼複用,我們可以將這些相同的參數集提取到一個單獨的解析器中,在創建其它解析器時通過parents指定父解析器,這樣新創建的解析器中就包含了相同的參數集。 -
formatter_class - A class for customizing the help output
通過 formatter_class 可以定製幫助信息 -
prefix_chars - The set of characters that prefix optional arguments (default: ‘-‘)
一般情況下,我們使用’-‘作爲選項前綴,ArgumentParser也支持自定義選項前綴,通過prefix_chars -
fromfile_prefix_chars - The set of characters that prefix files from which additional arguments should be read (default: None)
-
argument_default - The global default value for arguments (default: None)
-
conflict_handler - The strategy for resolving conflicting optionals (usually unnecessary)
-
add_help - Add a -h/–help option to the parser (default: True)
是否禁用-h –help選項
個人認爲常用的參數使用黑體標出,基本上如果沒有特別需求就指定一下description就可以了。
官網和一些參考文獻中都給出了每個參數的詳細定義和具體使用方法,這裏不在贅述。
add_argument()方法
ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
各個參數含義如下:
-
name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
指定一個可選參數或者位置參數。其中可選參數以-開頭,剩下的是位置參數 -
action - The basic type of action to be taken when this argument is encountered at the command line.
指定如何處理命令行參數 -
nargs - The number of command-line arguments that should be consumed.
指定多個命令行參數和一個arcion相關聯,具體見官方文檔 -
const - A constant value required by some action and nargs selections.
constant value,不是從命令行中讀取,在某些特定action中需要指定。 -
default - The value produced if the argument is absent from the command line.
如果參數可以缺省,default指定命令行參數不存在時的參數值。 -
type - The type to which the command-line argument should be converted.
默認情況下,ArgumentParser對象將命令行參數保存爲字符串。但通常命令行參數應該被解釋爲另一種類型,如 float或int。通過指定type,可以對命令行參數執行類型檢查和類型轉換 -
choices - A container of the allowable values for the argument.
將命令行參數的值限定在一個範圍內,超出範圍則報錯 -
required - Whether or not the command-line option may be omitted (optionals only).
指定命令行參數是否必需,默認通過-f –foo指定的參數爲可選參數。 -
help - A brief description of what the argument does.
幫助文檔 -
metavar - A name for the argument in usage messages.
寫幫助文檔時可選的參數 -
dest - The name of the attribute to be added to the object returned by parse_args().
dest 允許自定義ArgumentParser的參數屬性名稱
最後來個示範
常用的參數基本都列出來了,接下來用Pytorch源碼中的一個小例子演示用法:
parser = argparse.ArgumentParser(description='PyTorch MNIST Example')
parser.add_argument('--batch-size', type=int, default=64, metavar='N',
help='input batch size for training (default: 64)')
parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N',
help='input batch size for testing (default: 1000)')
parser.add_argument('--epochs', type=int, default=10, metavar='N',
help='number of epochs to train (default: 10)')
parser.add_argument('--lr', type=float, default=0.01, metavar='LR',
help='learning rate (default: 0.01)')
parser.add_argument('--momentum', type=float, default=0.5, metavar='M',
help='SGD momentum (default: 0.5)')
parser.add_argument('--no-cuda', action='store_true', default=False,
help='disables CUDA training')
parser.add_argument('--seed', type=int, default=1, metavar='S',
help='random seed (default: 1)')
parser.add_argument('--log-interval', type=int, default=10, metavar='N',
help='how many batches to wait before logging training status')
args = parser.parse_args()