zoukankan      html  css  js  c++  java
  • python-argparse

    官网文档
    https://docs.python.org/zh-cn/3/library/argparse.html#module-argparse
    https://www.jianshu.com/p/fef2d215b91d

    基本使用流程

    #1创建解析器 
    #ArgumentParser 对象包含将命令行解析成 Python 数据类型所需的全部信息
    parser = argparse.ArgumentParser(description='Process some integers.')
    
    #2添加参数
    #调用 add_argument() 方法
    parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
    
    #3解析参数
    #通过 parse_args() 方法解析参数
    args = parser.parse_args()
    

    ArgumentParser :

    class 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])
    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)
    
    

    add_argument() 方法

    ArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
    
    name or flags - 一个命名或者一个选项字符串的列表,例如 foo 或 -f, --foo。
    action - 当参数在命令行中出现时使用的动作基本类型。
    nargs - 命令行参数应当消耗的数目。
    const - 被一些 action 和 nargs 选择所需求的常数。
    default - 当参数未在命令行中出现时使用的值。
    type - 命令行参数应当被转换成的类型。
    choices - 可用的参数的容器。
    required - 此命令行选项是否可省略 (仅选项可用)。
    help - 一个此选项作用的简单描述。
    metavar - 在使用方法消息中使用的参数值示例。
    dest - 被添加到 parse_args() 所返回对象上的属性名
    
    
    

    使用方式

    位置参数positional arguments

    定位参数的,用法是不用带-就可用

    import argparse
    parser = argparse.ArgumentParser(description="Demo of argparse")
    parser.add_argument("echo",help="set echo value ")
    parser.add_argument("co", help="set kdjka  kadj")
    args = parser.parse_args()
    print("echo :", args.echo)
    print("co", args.co)
    
    ##输出
    usage: test.py [-h] echo co
    
    Demo of argparse
    
    positional arguments:
      echo        set echo value
      co          set kdjka kadj
    
    optional arguments:
      -h, --help  show this help message and exit
    
    ##定义了一个叫echo的参数,默认必选, 执行程序包含有参数,默认第一个参数赋值给echo ,第二个参数赋值给co,	类似于键值对
    
    

    可选参数optional arguments

    中文名叫可选参数,有两种方式:
    一种是通过一个-来指定的短参数,如-h;
    一种是通过--来指定的长参数,如--help

    可选参数,也就是命令行参数是可选的

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbosity", help="increase output verbosity")
    #parser.add_argument("-v", "--verbosity", help="increase output verbosity", default="vvvvv")
    #如果设置默认值,执行时不提供参数他也会自行产生
    parser.add_argument("-x", "--xerbosity", help="increase output verbosity")
    args = parser.parse_args()
    print(args)
    if args.verbosity:
            print("verbosity turned on")
            print(args.verbosity)
            
            
    ##执行
    $ python prog.py -v 1
    
    $ python prog.py --verbosity 1
    $ python prog.py -v 
    $ python test.py   
    Namespace(verbosity=None, xerbosity=None)
    
    
    ##可选参数意思是可以使用  -v  也可以使用--verbosity
    指定的值会保存在verbosity 中,通过args.verbosity  获取他的值
    Namespace中有两个属性(也叫成员)这里要注意个问题,当'-'和'--'同时出现的时候,系统默认后者为参数名,前者不是
    

    required

    这个参数是否一定需要设置

    ...
    parser.add_argument('-name', required=True)
    ...
    
    

    dest

    设置参数在代码中的变量名

    argparse默认的变量名是---后面的字符串,但是你也可以通过dest=xxx来设置参数的变量名,然后在代码中用args.xxx来获取参数的值

    nargs

    设置参数在使用可以提供的个数

    parser.add_argument('-name', nargs=x)
    其中x的候选值和含义如下:
    值  含义
    N   参数的绝对个数(例如:3)
    '?'   0或1个参数
    '*'   0或所有参数
    '+'   所有,并且至少一个参数
    ####示例
    
    # file-name: nargs.py
    import argparse
    
    def get_parser():
        parser = argparse.ArgumentParser(
            description='nargs demo')
        parser.add_argument('-name', required=True, nargs='+')
    
        return parser
    
    
    if __name__ == '__main__':
        parser = get_parser()
        args = parser.parse_args()
        names = ', '.join(args.name)
        print('Hello to {}'.format(names))
    
    

    action='store_true'

    对可选变量可以设置 action 参数。这个参数可以设置为如下值:

    • **store** 将输入的值保存到 Namespace 实例中。(这是默认操作)
    • **store_const** 当该可选变量在命令行被设置时,保存一个常数(需要用 const 指定,否则报错)。
    • **store_true** 当在命令行设置该可选变量时,将会给它绑定一个布尔值 True,若不设置,则该可选变量默认绑定 False
    • **store_false**store_true 表现相反,不设置绑定的是 True,显式设定后绑定 False
    • **append** 保存一个列表,每次设置这个变量,都会为列表添加一个值。
    • **append_const** 每次设置时给列表添加一个常量。
    • **count**保存一个整数,整数的值为该参数被设置的次数。
    • **help** 显示帮助文档并退出
    • **version** 显示程序版本并推出
    # actions_example.py
    import argparse
    
    my_parser = argparse.ArgumentParser()
    my_parser.version = '1.0'
    my_parser.add_argument('-a', action='store')
    my_parser.add_argument('-b', action='store_const', const=42)
    my_parser.add_argument('-c', action='store_true')
    my_parser.add_argument('-d', action='store_false')
    my_parser.add_argument('-e', action='append')
    my_parser.add_argument('-f', action='append_const', const=42)
    my_parser.add_argument('-g', action='count')
    my_parser.add_argument('-i', action='help')
    my_parser.add_argument('-j', action='version')
    
    args = my_parser.parse_args()
    
    print(vars(args))
    
    

    https://zhuanlan.zhihu.com/p/138294710

    类型 type

    argparse提供了对参数类型的解析,如果类型不符合,则直接报错

    #!/usr/bin/env python
    # encoding: utf-8
    import argparse
    
    parser = argparse.ArgumentParser()
    parser.add_argument('x', type=int, help="the base")
    args = parser.parse_args()
    answer = args.x ** 2
    print(answer)
    
    ##测试
    $ python prog.py 2
    
    
    

    可选值choices=[]

    如果要限定某个值的取值范围

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument("square", type=int,
                        help="display a square of a given number")
    parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                        help="increase output verbosity")
    args = parser.parse_args()
    answer = args.square**2
    if args.verbosity == 2:
        print("the square of {} equals {}".format(args.square, answer))
    elif args.verbosity == 1:
        print("{}^2 == {}".format(args.square, answer))
    else:
        print(answer)
    

    自定义帮助信息help

    parser.add_argument("square", type=int, help="display a square of a given number")
    打印输出

    positional arguments:
      square                display a square of a given number
    

    整个程序定义帮助文档

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    
    
    parser = argparse.ArgumentParser(description="calculate X to the power of Y")
    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", action="store_true")
    group.add_argument("-q", "--quiet", action="store_true")
    parser.add_argument("x", type=int, help="the base")
    parser.add_argument("y", type=int, help="the exponent")
    args = parser.parse_args()
    answer = args.x**args.y
    
    if args.quiet:
        print answer
    elif args.verbose:
        print "{} to the power {} equals {}".format(args.x, args.y, answer)
    else:
        print "{}^{} == {}".format(args.x, args.y, answer)
    
    
    #执行
    python prog.py -h
    usage: prog.py [-h] [-v | -q] x y
    
    calculate X to the power of Y
    
    positional arguments:
      x              the base
      y              the exponent
    
    optional arguments:
      -h, --help     show this help message and exit
      -v, --verbose
      -q, --quiet
    

    互斥参数

    group = parser.add_mutually_exclusive_group()
    group.add_argument("-v", "--verbose", action="store_true")
    group.add_argument("-q", "--quiet", action="store_true")
    
    # -v  和-q 
    
    
    

    参数默认值

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    
    
    parser = argparse.ArgumentParser(description="calculate X to the power of Y")
    parser.add_argument("square", type=int,
                        help="display a square of a given number")
    parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], default=1,
                        help="increase output verbosity")
    args = parser.parse_args()
    answer = args.square**2
    if args.verbosity == 2:
        print "the square of {} equals {}".format(args.square, answer)
    elif args.verbosity == 1:
        print "{}^2 == {}".format(args.square, answer)
    else:
        print(answer)
    

    设置外部参数文件的前缀字符

    当代码的命令行参数非常长时,把它们预先存放到外部文件中,运行程序时直接加载该文件是个好主意。argparse 通过设置 from_file_prefix_chars支持这一操作。

    # fromfile_example.py
    import argparse
    
    my_parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    
    my_parser.add_argument('a', help='a first argument')
    my_parser.add_argument('b', help='a second argument')
    my_parser.add_argument('c', help='a third argument')
    my_parser.add_argument('d', help='a fourth argument')
    my_parser.add_argument('e', help='a fifth argument')
    my_parser.add_argument('-v', '--verbose', action='store_true', help='an optional argument')
    
    args = my_parser.parse_args()
    print('If you read this line it means that you have provided all the parameters')
    

    创建一个 args.txt,包含所有必要的参数,每个参数占一行

    first
    second
    third
    fourth
    fifth
    

    执行

    $ python fromfile_example.py @args.txt
    
  • 相关阅读:
    [Debug]驱动程序调测方法与技巧
    [内核同步]自旋锁spin_lock、spin_lock_irq 和 spin_lock_irqsave 分析
    ios多线程-GCD基本用法
    用PHP抓取页面并分析
    IOS开发-KVC
    IOS开发-KVO
    JavaScript垃圾回收(三)——内存泄露
    JavaScript垃圾回收(二)——垃圾回收算法
    JavaScript垃圾回收(一)——内存分配
    JavaScript闭包(二)——作用
  • 原文地址:https://www.cnblogs.com/g2thend/p/12539618.html
Copyright © 2011-2022 走看看