關於argparse庫的個人學習
阿新 • • 發佈:2018-03-18
type flags font 通過 選擇 orm 位置 pos roc
在python 中 通過命令行進行解析,(sys.argv 也可以簡單實現)。
python官網 有詳解 :https://docs.python.org/3.6/library/argparse.html?highlight=parser%20argparse%20argumentparser#module-argparse
使用方法:
1 import argparse 2 3 parser = argparse.ArgumentParser(description=‘Process some integers.‘) 4 parser.add_argument(‘integers‘, metavar=‘N‘, type=int, nargs=‘+‘, 5 help=‘an integer for the accumulator‘) 6 parser.add_argument(‘--sum‘, dest=‘accumulate‘, action=‘store_const‘, 7 const=sum, default=max, 8 help=‘sum the integers (default: find the max)‘) 9 10 args = parser.parse_args()
== 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, allow_abbrev=True)
prog - 項目的名字(缺省值為 sys.argv[0])
description - 在獲取參數時 顯示文本
其余參數 未使用 待補充;
==
Parser.
add_argument
(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
1,name or flags :好像得傳入一個 optional argument(選擇參數?like ‘-fo’ , ‘-foo’) 或者位置參數
官網的就很好理解
1 >>> parser = argparse.ArgumentParser(prog=‘PROG‘) 2 >>> parser.add_argument(‘-f‘, ‘--foo‘) 3 >>> parser.add_argument(‘bar‘) 4 >>> parser.parse_args([‘BAR‘]) 5 Namespace(bar=‘BAR‘, foo=None) 6 >>> parser.parse_args([‘BAR‘, ‘--foo‘, ‘FOO‘]) 7 Namespace(bar=‘BAR‘, foo=‘FOO‘) 8 >>> parser.parse_args([‘--foo‘, ‘FOO‘]) 9 usage: PROG [-h] [-f FOO] bar 10 PROG: error: too few arguments
The parse_args() method:(args=None, namespace=None)
待補充;
關於argparse庫的個人學習