python 模块argparse用法实

发布时间:2019-08-28 09:10:29编辑:auto阅读(1779)

     argparse是python内置模块,用于快速创建命令行。有一个第三方模块Click也可以实现这个功能,两者各有优缺点,看个人需求吧。


    官方网页

    https://docs.python.org/3.5/library/argparse.html

    import  argparse
    __version__ = '1.1.1'
    parser = argparse.ArgumentParser(description='hahahaaaa')
    parser.add_argument('-V', '--version', action='version', version='%(prog)s '+__version__)
    parser.add_argument('--name','-n',metavar='namemma',dest='name',type=str,help='your name',nargs=1)
    parser.add_argument('-i',metavar='III',action='store_const',dest='iiii',const='ii',help="dfafsdf")
    parser.add_argument("-z", choices=['a', 'b', 'd'],required=False)
    parser.add_argument('foo')
    args = parser.parse_args()
    
    print(type(args))
    print(args.name,args.iiii,args.foo)

    ArgumentParser参数的简单说明

     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信息都是必须的,所以不用设置啦。

     

    add_argument:读入命令行参数,该调用有多个参数

    ArgumentParser.add_argument(name or flags…[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

    name or flags:是必须的参数,该参数接受选项参数或者是位置参数(一串文件名)


    不带'--'的参数

        调用脚本时必须输入值

        参数输入的顺序与程序中定义的顺序一致

    '-'的参数

        可不输入    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)

        metavar: 参数的名字,在显示 帮助信息时才用到.

        action:

            store:默认action模式,存储值到指定变量。

            store_const:存储值在参数的const部分指定,多用于实现非布尔的命令行flag。

            store_true / store_false:布尔开关。可以2个参数对应一个变量。

            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:通常-f这样的选项是可选的,但是如果required=True那么就是必须的了

        nsrgs 用来指定参数的个数,可以是1,2,3....也可以是?或*或+

            ? 零个或一个

            * 零个或多个

            + 一个或多个


    创建子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()


关键字