python-argparse使用
python-argparse使用
官方文檔:https://docs.python.org/zh-cn/3.7/library/argparse.html?highlight=argparse#module-argparse
argparse 模塊可以編輯用戶友好的命令行接口
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))1.創建一個解析器
parser = argparse.ArgumentParser(description='Process som integers.')
ArgumentParser對象包含將命令行解析成Python數據類型所需的全部信息
"""Object for parsing command line strings into Python objects.- prog - 程序的名稱(默認:sys.argv[0])
- usage - 描述程序用途的字符串(默認值:從添加到解析器的參數生成)
- description - 在參數幫助文檔之前顯示的文本(默認值:無)
- epilog - 在參數幫助文檔之后顯示的文本(默認值:無)
- parents - 一個 ArgumentParser 對象的列表,它們的參數也應包含在內
- formatter_class - 用于自定義幫助文檔輸出格式的類
- prefix_chars - 可選參數的前綴字符集合(默認值:'-')
- fromfile_prefix_chars - 當需要從文件中讀取其他參數時,用于標識文件名的前綴字符集合(默認值:None)
- argument_default - 參數的全局默認值(默認值: None)
- conflict_handler - 解決沖突選項的策略(通常是不必要的)
- add_help - 為解析器添加一個 -h/--help 選項(默認值: True)
- allow_abbrev - 如果縮寫是無歧義的,則允許縮寫長選項 (默認值:True)
2.添加參數
給ArgumentParser添加程序參數是通過調用add_argument()方法完成的,通常這些調用指定ArgumentParser如何過去命令行參數并將其轉化為對象。這些信息在parse_args()調用時存儲和使用
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)')當調用parser.parse_args()將返回一個具有integers和accumulate兩個屬性的對象。integers屬性將是一個包含一個或者多個整數的列表,而accumulate 屬性當命令行中指定了 --sum參數時,將是sum()函數,否則則是max()函數。
add_argument()方法:
name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo. action - 將命令行參數和操作關聯操作:store:默認操作,將參數存儲parser.add_argument('--foo')parser.parse_args('--foo 1'.split())->Namespace(foo='1')store_const:這個操作將存儲const關鍵字指定的值parser.add_argument('--foo', action='store_const', const=42)parser.parse_args(['--foo'])->Namespace(foo=42)store_true & store_false:這兩個操作是store_const中的特殊操作,將創建默認的值:False/Trueparser.add_argument('--foo',action='store_true')parser.add_argument('--bar',action='store_false')parser.add_argument('--baz',action='store_false')parser.parse_args('--foo --bar'.split())->Namespace(foo=True,bar=False,baz=True)append:這個操作將命令行參數存儲為一個集合parser.add_argument('--foo',action='append')parser.parse_args('--foo 1 --foo 2'.split())->Namespace(foo=['1','2,])append_const:這將存儲一個列表,并將const關鍵字參數指定的值附加到該列表。(注意,const關鍵字參數默認為none。)當多個參數需要將常量存儲到同一列表時,“append-const”操作通常很有用parser.add_argument('--str', dest='types', action='appent_const',const=str)parser.add_argument('--int', dest='types', action='append_const',const=int)parser.parse_args('--str --int'.split())->Namespace(types=[<class 'str'>,<class 'int'>])count:統計命令行參數中出現的次數parser.add_argument(‘--verbose','-v',action='count')parser.parse_args(['-vvv'])->Namespace(verbose=3).nargs - 將不同數量的命令行參數與單個操作關聯. parser.add_argument('--foo',nargs=2)parser.add_argument('bar',nargs=1)parser.parse_args('c --foo a b'.split())->Namespace(bar=['c'],foo=['a','b']) const - 某些action和nargs選項要求的常數值。 default - 如果命令行中沒有出現該參數時的默認值。 type - 命令行參數應該被轉換成的類型。 choices - 參數可允許的值的一個容器。 required - 該命令行選項是否可以省略(只針對可選參數)。 help - 參數的簡短描述。 metavar - 參數在幫助信息中的名字。 dest - 給parse_args()返回的對象要添加的屬性名稱。
?
3.解析參數
ArgumentParser通過parser_args()方法解析參數。它將檢查命令行,把每個參數轉換為適當的類型然后調用響應的操作。 大多數情況下,將常見一個Namespace對象
parser.parse_args(['--sum','7','-1','42']) ->Namespace(accumulate=<built -in function sum>, integers=[7,-1,42])在腳本中parse_args()方法是不用帶參數的,而是自動從sys.argv中確定命令行參數
?
其他博客:https://www.cnblogs.com/piperck/p/8446580.html
posted @ 2019-04-03 15:16 巡山小妖N 閱讀(...) 評論(...) 編輯 收藏
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的python-argparse使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LinkedList阅读
- 下一篇: python-argparse批量修改后