1. 程式人生 > >python中的argparse模組(引數解析)

python中的argparse模組(引數解析)

import argparse
parse = argparse.ArgumentParser()
parse.add_argument("a", help="params means")
parse.add_argument("-C", "--gc", default="count")
parse.add_argument("--ga", help="params means ga",dest='simple_value',choices=['A', 'B', 'C', 0])
parse.add_argument("--gb", help="params means gb",action="store_const",const='value-to-store')

args = parse.parse_args()
print args.simple_value,args.gb,args.gc

### add_argument 說明
不帶'--'的引數
    呼叫指令碼時必須輸入值
    引數輸入的順序與程式中定義的順序一致
'-'的引數
    可不輸入    add_argument("-a")
    類似有'--'的shortname,但程式中的變數名為定義的引數名
'--'引數
    引數別名: 只能是1個字元,區分大小寫
        add_argument("-shortname","--name", help="params means"),但程式碼中不能使用shortname
    dest: 引數在程式中對應的變數名稱 add_argument("a",dest='code_name')
    default: 引數預設值
    help: 引數作用解釋  add_argument("a", help="params means")
    type : 預設string  add_argument("c", type=int)
    action:
    store:預設action模式,儲存值到指定變數。
    store_const:儲存值在引數的const部分指定,多用於實現非布林的命令列flag。
    store_true / store_false:布林開關。 store_true.預設為False,輸入則為true。 store_flase 相反
    append:儲存值到列表,該引數可以重複使用。
    append_const:儲存值到列表,儲存值在引數的const部分指定。
    count: 統計引數簡寫輸入的個數  add_argument("-c", "--gc", action="count")
    version 輸出版本資訊然後退出。
    const:配合action="store_const|append_const"使用,預設值
    choices:輸入值的範圍 add_argument("--gb", choices=['A', 'B', 'C', 0])
    required : 預設False, 若為 True, 表示必須輸入該引數


==================================================================================
    Keyword Arguments:
        - option_strings -- A list of command-line option strings which    should be associated with this action.
        - dest -- The name of the attribute to hold the created object(s)
        - nargs -- The number of command-line arguments that should be  consumed. By default, one argument will be consumed and a single  value will be produced.
                     Other values include:
                - N (an integer) consumes N arguments (and produces a list)
                - '?' consumes zero or one arguments
                - '*' consumes zero or more arguments (and produces a list)
                - '+' consumes one or more arguments (and produces a list)
                    Note that the difference between the default and nargs=1 is that with the default, a single value will be produced, while with  nargs=1, a list containing a single value will be produced.
        - const -- The value to be produced if the option is specified and the  option uses an action that takes no values.
        - default -- The value to be produced if the option is not specified.
        - type -- A callable that accepts a single string argument, and returns the converted value.  
                    The standard Python types str, int,  float, and complex are useful examples of such callables.  If None,  str is used.
        - choices -- A container of values that should be allowed.
                    If not None,  after a command-line argument has been converted to the appropriate type, an exception will be raised if it is not a member of this collection.
        - required -- True if the action must always be specified at the command line. This is only meaningful for optional command-line  arguments.
        - help -- The help string describing the argument.
        - metavar -- The name to be used for the option's argument with the  help string. If None, the 'dest' value will be used as the name.


  • 建立子parse,每個子parse對應自己的輸入引數
  

點選(此處)摺疊或開啟

import argparse

# sub-command functions

def subcmd_list(args):
   print "list"

def subcmd_create(args):

   print "create"

def subcmd_delete(args):

   print "delete"

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help='commands')
# A list command
list_parser = subparsers.add_parser('list', help='Listcontents')
list_parser.add_argument('dirname', action='store', help='Directory tolist')
list_parse.set_defaults(func=subcmd_list)

# A create command
create_parser = subparsers.add_parser('create', help='Create a directory')
create_parser.add_argument('dirname',action='store',help='New directoryto create')
create_parser.add_argument('--read-only',default=False, action='store_true',help='Setpermissions to prevent writing to the directory')
create_parser .set_defaults(func=subcmd_create)

# A delete command
delete_parser = subparsers.add_parser('delete',help='Remove a directory')
delete_parser.add_argument( 'dirname', action='store',help='The directory to remove')
delete_parser.add_argument('--recursive', '-r',default=False, action='store_true',help='Remove thecontents of the directory, too')
delete_parser .set_defaults(func=subcmd_delete)

args = parser.parse_args()
# call subcmd
args.fun(args)


使用幫助
# python args_subparse.py -h
usage: args_subparse.py [-h] {create,list,delete} ...

positional arguments:
  {create,list,delete}  commands
    list                Listcontents
    create              Create a directory
    delete              Remove a directory

optional arguments:
  -h, --help            show this help message and exit
  
# python args_subparse.py create -h
usage: args_subparse.py create [-h] [--read-only] dirname

positional arguments:
  dirname      New directoryto create

optional arguments:
  -h, --help   show this help message and exit
  --read-only  Setpermissions to prevent writing to the directory
  
# python args_subparse.py delete -h
usage: args_subparse.py delete [-h] [--recursive] dirname

positional arguments:
  dirname          The directory to remove

optional arguments:
  -h, --help       show this help message and exit
  --recursive, -r  Remove thecontents of the directory, too
 
# python args_subparse.py list -h
usage: args_subparse.py list [-h] dirname

positional arguments:
  dirname     Directory tolist

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

多個subparser 使用同樣定義的引數
# add_help=False,必須指定,否則報-h重複定義
parents_parser = argparse.ArgumentParser(add_help=False)
parents_parser.add_argument('--foo', dest="foo", action='store_true')
parents_parser.add_argument('--bar', dest="bar", action='store_false')
parents_parser.add_argument('--baz', dest="baz", action='store_false')

parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(help='commands')
m_parser = subparsers.add_parser("mysql", parents=[parents_parser], help="mysql method")
m_parser.set_defaults(func=sub_mysql)
o_parser = subparsers.add_parser("oracle", parents=[parents_parser], help="oracle method")
o_parser.set_defaults(func=sub_oracle)
args = parser.parse_args()


參考
http://blog.csdn.net/songuooo/article/details/8373086
http://www.2cto.com/kf/201208/149418.html
http://stackoverflow.com/questions/7498595/python-argparse-add-argument-to-multiple-subparsers