python標准庫sys模塊
sys.argv #命令行參數List,第一個元素是程序本身路徑
sys.exit(n) #退出程序,正常退出時exit(0)
sys.version #獲取Python解釋程序的版本信息
sys.maxint # 最大的Int值
sys.path #返回模塊的搜索路徑,初始化時使用PYTHONPATH環境變量的值
sys.platform #返回操作系統平台名稱
sys.stdin #輸入相關
sys.stdout #輸出相關
sys.stderror #錯誤相關
argparse模塊
作用: argparse 是 Python 內置的一個用於命令項選項與參數解析的模塊,通過在程序中定義好我們需要的參數,argparse 將會從 sys.argv 中解析出這些參數,並自動生成幫助和使用信息。當然,Python 也有第三方的庫可用於命令行解析,而且功能也更加強大,比如 docopt,Click。
1. 命令行參數分為位置參數和選項參數:
- 位置參數就是程序根據該參數出現的位置來確定的
- 如:[root@openstack_1 /]# ls root/ #其中root/是位置參數
- 選項參數是應用程序已經提前定義好的參數,不是隨意指定的
- 如:[root@openstack_1 /]# ls -l # -l 就是ls命令里的一個選項參數
2. 使用步驟:
(1)import argparse 首先導入模塊
(2)parser = argparse.ArgumentParser() 創建一個解析對象
(3)parser.add_argument() 向該對象中添加你要關注的命令行參數和選項
(4)parser.parse_args() 進行解析
argparse.ArgumentParser()方法參數須知:一般我們只選擇用description
- description - 命令行幫助的開始文字,大部分情況下,我們只會用到這個參數
- epilog - 命令行幫助的結尾文字
- prog - (default: sys.argv[0])程序的名字,一般不需要修改,另外,如果你需要在help中使用到程序的名字,可以使用%(prog)s
- prefix_chars - 命令的前綴,默認是-,例如-f/–file。有些程序可能希望支持/f這樣的選項,可以使用prefix_chars=”/”
- fromfile_prefix_chars - (default: None)如果你希望命令行參數可以從文件中讀取,就可能用到。例如,如果fromfile_prefix_chars=’@’,命令行參數中有一個為”@args.txt”,args.txt的內容會作為命令行參數
- add_help - 是否增加-h/-help選項 (default: True),一般help信息都是必須的,所以不用設置啦。
- parents - 類型是list,如果這個parser的一些選項跟其他某些parser的選項一樣,可以用parents來實現繼承,例如parents=[parent_parser]
- 三個允許的值: # class argparse.RawDescriptionHelpFormatter 直接輸出description和epilog的原始形式(不進行自動換行和消除空白的操作) # class argparse.RawTextHelpFormatter 直接輸出description和epilog以及add_argument中的help字符串的原始形式(不進行自動換行和消除空白的操作) # class argparse.ArgumentDefaultsHelpFormatter 在每個選項的幫助信息后面輸出他們對應的缺省值,如果有設置的話。這個最常用吧!
- argument_default - (default: None)設置一個全局的選項的缺省值,一般每個選項單獨設置,所以這個參數用得少,不細說
- usage - (default: generated)如果你需要修改usage的信息(usage: PROG [-h] [–foo [FOO]] bar [bar …]),那么可以修改這個,一般不要修改。
- conflict_handler - 不建議使用。這個在極端情況下才會用到,主要是定義兩個add_argument中添加的選項的名字發生沖突時怎么處理,默認處理是拋出異常。
4. add_argument()方法參數須知:
- name or flags - 指定參數的形式,想寫幾個寫幾個,不過我們一般就寫兩個,一個短參數,一個長參數,看下面的例子”-f”, “–file”
- 可選的選項,位置不固定,想怎么寫就怎么寫,默認是可選的 # parser.add_argument(“-f”, “–file”, help=”test test test”)
- 位置固定的選項,例如”prog i_am_bar”,這樣子的話,i_am_bar就是bar選項的值啦,默認是必須有的 # parser.add_argument(“bar”, help=”test test test”)
- nargs - 指定這個參數后面的value有多少個,例如,我們希望使用-n 1 2 3 4,來設置n的值為[1, 2, 3, 4] #parser.add_argument(“-n”, “–num”, nargs=”+”, type=int) # 這里nargs=”+”表示,如果你指定了-n選項,那么-n后面至少要跟一個參數,+表示至少一個,?表示一個或0個,0個或多個 。
- default - 如果命令行沒有出現這個選項,那么使用default指定的默認值 #parser.add_argument(“+g”, “++gold”, help=”test test test”,default=”test_gold”)#需要prefix_chars包含”+” 。
- type - 如果希望傳進來的參數是指定的類型(例如 float, int or file等可以從字符串轉化過來的類型),可以使用 #parser.add_argument(“-x”, type=int) 。
- choices - 設置參數值的范圍,如果choices中的類型不是字符串,記得指定type哦 #parser.add_argument(“-y”, choices=[‘a’, ‘b’, ‘d’])
- required - 通常-f這樣的選項是可選的,但是如果required=True那么就是必須的了 #parser.add_argument(“-z”, choices=[‘a’, ‘b’, ‘d’], required=True)
- metavar - 參數的名字,在顯示 幫助信息時才用到. # parser.add_argument(“-o”, metavar=”OOOOOO”)
- help - 設置這個選項的幫助信息
- dest - 設置這個選項的值就是解析出來后放到哪個屬性中 #parser.add_argument(“-q”, dest=”world”)
- args = parser.parse_args(args) # 如果你沒有args參數,那么就使用sys.argv,也就是命令行參數啦。有這個參數,就方便我們調試啊 。# args.world就是-q的值啦
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('echo') # add_argument()指定程序可以接受的命令行選項
args = parser.parse_args() # parse_args()從指定的選項中返回一些數據
print(args)
print(args.echo)
parser = argparse.ArgumentParser(description = 'this is a description')
parser.add_argument('--ver', '-v', action = 'store_true', help = 'hahaha')
# 將變量以標簽-值的字典形式存入args字典
args = parser.parse_args()
if args.ver:
print("Ture")
else:
print("False")
# required標簽就是說--ver參數是必需的,並且類型為int,輸入其它類型會報錯
parser.add_argument('--ver', '-v', required = True, type = int)
parser.add_argument('file', choices = ['test1', 'test2'])
args = parser.parse_args()
print('read in %s'%(args.file))
# 表示腳本可以讀入兩個整數賦予num鍵(此時的值為2個整數的數組)
parser.add_argument('filename', nargs = 2, type = int)
args = parser.parse_args()
print('read in %s'%(args.filename))
分析:nargs還可以’*‘用來表示如果有該位置參數輸入的話,之后所有的輸入都將作為該位置參數的值;‘+’表示讀取至少1個該位置參數。’?'表示該位置參數要么沒有,要么就只要一個。(PS:跟正則表達式的符號用途一致。)
如:
parser.add_argument('filename', nargs = '+', type = int)
args = parser.parse_args()
print('read in %s'%(args.filename))
dest - 設置這個選項的value解析出來后放到哪個屬性中
parser.add_argument('-file', choices = ['test1', 'test2'], dest = 'world')
args = parser.parse_args()
print('read in %s'%(args.world))
action參數
argparse內置6種動作可以在解析到一個參數時進行觸發:
store 保存參數值,可能會先將參數值轉換成另一個數據類型。若沒有顯式指定動作,則默認為該動作。
store_const 保存一個被定義為參數規格一部分的值,而不是一個來自參數解析而來的值。這通常用於實現非布爾值的命令行標記。
store_ture/store_false 保存相應的布爾值。這兩個動作被用於實現布爾開關。
append 將值保存到一個列表中。若參數重復出現,則保存多個值。
append_const 將一個定義在參數規格中的值保存到一個列表中。
version 打印關於程序的版本信息,然后退出
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-s', action='store', dest='simple_value',
help='Store a simple value')
parser.add_argument('-c', action='store_const', dest='constant_value',
const='value-to-store',
help='Store a constant value')
parser.add_argument('-t', action='store_true', default=False,
dest='boolean_switch',
help='Set a switch to true')
parser.add_argument('-f', action='store_false', default=False,
dest='boolean_switch',
help='Set a switch to false')
parser.add_argument('-a', action='append', dest='collection',
default=[],
help='Add repeated values to a list')
parser.add_argument('-A', action='append_const', dest='const_collection',
const='value-1-to-append',
default=[],
help='Add different values to list')
parser.add_argument('-B', action='append_const', dest='const_collection',
const='value-2-to-append',
help='Add different values to list')
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
results = parser.parse_args()
print 'simple_value =', results.simple_value
print 'constant_value =', results.constant_value
print 'boolean_switch =', results.boolean_switch
print 'collection =', results.collection
print 'const_collection =', results.const_collection
$ python argparse_action.py -h
usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f]
[-a COLLECTION] [-A] [-B] [--version]
optional arguments:
-h, --help show this help message and exit
-s SIMPLE_VALUE Store a simple value
-c Store a constant value
-t Set a switch to true
-f Set a switch to false
-a COLLECTION Add repeated values to a list
-A Add different values to list
-B Add different values to list
--version show program's version number and exit
$ python argparse_action.py -s value
simple_value = value
constant_value = None
boolean_switch = False
collection = []
const_collection = []
$ python argparse_action.py -c
simple_value = None
constant_value = value-to-store
boolean_switch = False
collection = []
const_collection = []
$ python argparse_action.py -t
simple_value = None
constant_value = None
boolean_switch = True
collection = []
const_collection = []
$ python argparse_action.py -f
simple_value = None
constant_value = None
boolean_switch = False
collection = []
const_collection = []
$ python argparse_action.py -a one -a two -a three
simple_value = None
constant_value = None
boolean_switch = False
collection = ['one', 'two', 'three']
const_collection = []
$ python argparse_action.py -B -A
simple_value = None
constant_value = None
boolean_switch = False
collection = []
const_collection = ['value-2-to-append', 'value-1-to-append']
$ python argparse_action.py --version
argparse_action.py 1.0
原文鏈接:https://blog.csdn.net/qq_36653505/article/details/83788460
