Python argparse 處理命令行小結

Python argparse 處理命令行小結python

1. 關於argparse
是python的一個命令行解析包,主要用於處理命令行參數測試

 

2. 基本用法
test.py是測試文件,其內容以下:ui

import argparse
parser = argparse.ArgumentParser()
parser.parse_args()

測試:
/home $ python test.py
/home $ python test.py --help
usage: test.py [-h]
optional arguments:
-h, --help show this help message and exit

/home $ python test.py -v 
usage: test.py [-h]
test.py: error: unrecognized arguments: -v

/home $ python test.py tt
usage: test.py [-h]
test.py: error: unrecognized arguments: tt

第一個沒有任何輸出和出錯
第二個測試爲打印幫助信息,argparse會自動生成幫助文檔
第三個測試爲未定義的-v參數,會出錯
第四個測試爲未定義的參數tt,出錯this

 

3. positional argumentsspa

修改test.py的內容以下:命令行

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo

測試:
/home $ python test.py 
usage: test.py [-h] echo
test.py: error: too few arguments

/home $ python test.py -h
usage: test.py [-h] echo

positional arguments:
echo

optional arguments:
-h, --help show this help message and exit

/home $ python test.py tt
tt

定義了一個叫echo的參數,默認必選code

第一個測試爲不帶參數,因爲echo參數爲空,因此報錯,並給出用法(usage)和錯誤信息
第二個測試爲打印幫助信息
第三個測試爲正經常使用法,回顯了輸入字符串ttorm

 

4. optional argumentsblog

中文名叫可選參數,有兩種方式:
一種是經過一個-來指定的短參數,如-h;
一種是經過--來指定的長參數,如--help
這兩種方式能夠同存,也能夠只存在一個,修改test.py內容以下:ip

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-v", "--verbosity", help="increase output verbosity")
args = parser.parse_args()
if args.verbosity:
print "verbosity turned on"

注意這一行:parser.add_argument("-v", "--verbosity", help="increase output verbosity")
定義了可選參數-v或--verbosity,經過解析後,其值保存在args.verbosity變量中
用法以下:

/home $ python test.py -v 1
verbosity turned on

/home $ python test.py --verbosity 1
verbosity turned on

/home $ python test.py -h 
usage: test.py [-h] [-v VERBOSITY]

optional arguments:
-h, --help show this help message and exit
-v VERBOSITY, --verbosity VERBOSITY
increase output verbosity

/home $ python test.py -v 
usage: test.py [-h] [-v VERBOSITY]
test.py: error: argument -v/--verbosity: expected one argument

測試1中,經過-v來指定參數值

測試2中,經過--verbosity來指定參數值
測試3中,經過-h來打印幫助信息
測試4中,沒有給-v指定參數值,因此會報錯

 

5. action='store_true'
上一個用法中-v必須指定參數值,不然就會報錯,有沒有像-h那樣,不須要指定參數值的呢,答案是有,經過定義參數時指定action="store_true"便可,用法以下

import argparse parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true") args = parser.parse_args() if args.verbose: print "verbosity turned on" 測試: /home $ python test.py -v verbosity turned on /home $ python test.py -h usage: test.py [-h] [-v] optional arguments: -h, --help show this help message and exit -v, --verbose increase output verbosity

第一個例子中,-v沒有指定任何參數也可,其實存的是True和False,若是出現,則其值爲True,不然爲False

 

6. 類型 type
默認的參數類型爲str,若是要進行數學計算,須要對參數進行解析後進行類型轉換,若是不能轉換則須要報錯,這樣比較麻煩
argparse提供了對參數類型的解析,若是類型不符合,則直接報錯。以下是對參數進行平方計算的程序:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('x', type=int, help="the base")
args = parser.parse_args()
answer = args.x ** 2
print answer

測試:
/home $ python test.py 2
4
/home $ python test.py two
usage: test.py [-h] x
test.py: error: argument x: invalid int value: 'two'

/home $ python test.py -h 
usage: test.py [-h] x

positional arguments:
x the base

optional arguments:
-h, --help show this help message and exit

第一個測試爲計算2的平方數,類型爲int,正常
第二個測試爲一個非int數,報錯
第三個爲打印幫助信息

 

7. 可選值choices=[]
5中的action的例子中定義了默認值爲True和False的方式,若是要限定某個值的取值範圍,好比6中的整形,限定其取值範圍爲0, 1, 2,該如何進行呢?
修改test.py文件以下:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer

測試:
/home $ python test.py 4 -v 0
16
/home $ python test.py 4 -v 1
4^2 == 16
/home $ python test.py 4 -v 2
the square of 4 equals 16
/home $ python test.py 4 -v 3
usage: test.py [-h] [-v {0,1,2}] square
test.py: error: argument -v/--verbosity: invalid choice: 3 (choose from 0, 1, 2)
/home $ python test.py -h
usage: test.py [-h] [-v {0,1,2}] square

positional arguments:
square display a square of a given number

optional arguments:
-h, --help show this help message and exit
-v {0,1,2}, --verbosity {0,1,2}
increase output verbosity

測試1, 2, 3 爲可選值範圍,經過其值,打印不一樣的格式輸出;
測試4的verbosity值不在可選值範圍內,打印錯誤
測試5打印幫助信息

 

8. 自定義幫助信息help
上面不少例子中都爲help賦值,如
parser.add_argument("square", type=int, help="display a square of a given number")
在打印輸出時,會有以下內容

positional arguments:
square display a square of a given number
也就是help爲何,打印輸出時,就會顯示什麼

 

9. 程序用法幫助
8中介紹了爲每一個參數定義幫助文檔,那麼給整個程序定義幫助文檔該怎麼進行呢?
經過argparse.ArgumentParser(description="calculate X to the power of Y")便可
修改test.py內容以下:

import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
parser.add_argument("x", type=int, help="the base")
parser.add_argument("y", type=int, help="the exponent")
args = parser.parse_args()
answer = args.x**args.y

if args.quiet:
print answer
elif args.verbose:
print "{} to the power {} equals {}".format(args.x, args.y, answer)
else:
print "{}^{} == {}".format(args.x, args.y, answer)

打印幫助信息時即顯示calculate X to the power of Y

/home $ python test.py -h
usage: test.py [-h] [-v | -q] x y

calculate X to the power of Y

positional arguments:
x the base
y the exponent

optional arguments:
-h, --help show this help message and exit
-v, --verbose
-q, --quiet

 

10. 互斥參數

在上個例子中介紹了互斥的參數

group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", action="store_true")
group.add_argument("-q", "--quiet", action="store_true")
第一行定義了一個互斥組,第2、三行在互斥組中添加了-v和-q兩個參數,用上個例子中的程序進行以下測試:

/home $ python test.py 4 2 
4^2 == 16
/home $ python test.py 4 2 -v
4 to the power 2 equals 16
/home $ python test.py 4 2 -q
16
/home $ python test.py 4 2 -q -v

能夠看出,-q和-v不出現,或僅出現一個均可以,同時出現就會報錯。
可定義多個互斥組

 

11.參數默認值
介紹了這麼多,有沒有參數默認值該如何定義呢?
修改test.py內容以下:

import argparse
parser = argparse.ArgumentParser(description="calculate X to the power of Y")
parser.add_argument("square", type=int,
help="display a square of a given number")
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], default=1,
help="increase output verbosity")
args = parser.parse_args()
answer = args.square**2
if args.verbosity == 2:
print "the square of {} equals {}".format(args.square, answer)
elif args.verbosity == 1:
print "{}^2 == {}".format(args.square, answer)
else:
print answer

測試:
/home $ python test.py 8 
8^2 == 64
/home $ python test.py 8 -v 0
64
/home $ python test.py 8 -v 1
8^2 == 64
/home $ python test.py 8 -v 2
the square of 8 equals 64

能夠看到若是不指定-v的值,args.verbosity的值默認爲1,爲了更清楚的看到默認值,也能夠直接打印進行測試。

相關文章
相關標籤/搜索