python3中argparse模块详解

文章目录

  • python3中argparse模块详解
  • 一. 命令行参数分为位置参数和选项参数:
  • 二. 使用步骤:
  • 三. add_argument()方法参数:
  • 1. name or flags:
  • 2. nargs参数:
  • 3. default参数:
  • 4. type参数:
  • 5. choices参数:
  • 6. required参数:
  • 7. metavar参数:
  • 8. help参数:
  • 9. dest参数:
  • 10. const参数:
  • 11. action参数:
  • 四. argparse.ArgumentParser()(可以忽略)
  • python3中argparse模块详解

    作用: argparse 是 Python 内置的一个用于命令项选项与参数解析的模块,通过在程序中定义好我们需要的参数,argparse 将会从 sys.argv 中解析出这些参数,并自动生成帮助和使用信息。

    一. 命令行参数分为位置参数和选项参数:

  • 位置参数就是程序根据该参数出现的位置来确定的;
  • 选项参数是应用程序已经提前定义好的参数,不是随意指定的
  • 二. 使用步骤:

    #(1) 首先导入模块;
    import argparse
    #(2)创建一个解析对象
    parser = argparse.ArgumentParser() 
    #(3)向该对象中添加你要关注的命令行参数和选项
    parser.add_argument() 
    #(4)进行解析
    parser.parse_args() 
    

    三. add_argument()方法参数:

    ArgumentParser.add_argument(name or flags...,
                                action='',
                                nargs='',
                                const,
                                default,
                                type,
                                choices,
                                required,
                                help,
                                metavar,
                                dest)
    

    1. name or flags:

    指定参数的形式,想写几个写几个,不过我们一般就写两个,一个短参数,一个长参数,看下面的例子”-f”, “–file”

  • 可选的选项,位置不固定,想怎么写就怎么写,默认是可选的,举例如下:
  •  parser.add_argument(“-f”, “–file”, help=”test”)
    
  • 位置固定的选项,例如:下面的代码,输入“python test.py barString”,这样子的话,barString就是args.filename选项的值啦,默认是必须有的:
  • parser.add_argument('filename')    # 输入的第一个参数赋予名为filename的键
    args = parser.parse_args()
    print("Read in %s" %(args.filename))
    

    2. nargs参数:

            指定这个参数后面的value有多少个,例如,我们希望使用-n 1 2 3 4,来设置n的值为[1, 2, 3, 4];
            nargs:还可以’*‘用来表示如果有该位置参数输入的话,之后所有的输入都将作为该位置参数的值;‘+’表示读取至少1个该位置参数;’?'表示该位置参数要么没有,要么就只要一个。(PS:跟正则表达式的符号用途一致。)

    #这里nargs=”+”表示,如果你指定了-n选项,那么-n后面至少要跟一个参数,+表示至少一个,?表示一个或0个,0个或多个 。
    parser.add_argument(“-n”, “–num”, nargs=”+”, type=int) 
    # 运行python test.py text.txt 1 2
    # 由于没有标签,所以用位置参数的时候需要比较小心。
    parser.add_argument('filename')
    parser.add_argument('num', nargs='*)
    

    3. default参数:

    如果命令行没有出现这个选项,那么使用default指定的默认值:

    parser.add_argument('filename', default='text.txt')
    args = parser.parse_args()
    print("Read in %s" %(args.filename))
    

            这个时候至直接运行python text.py就能得到Read in text.txt而不需要输入文件名了。

    4. type参数:

    如果希望传进来的参数是指定的类型(例如 float, int or file等可以从字符串转化过来的类型)

    parser.add_argument(“-x”, type=int) 
    

    5. choices参数:

    设置参数值的范围,如果choices中的类型不是字符串,记得指定type。

    parser.add_argument(“-y”, choices=[‘a’, ‘b’, ‘d’])
    

    6. required参数:

    通常-f这样的选项是可选的,但是如果required=True那么就是必须的了。

    parser.add_argument(“-z”, choices=[‘a’, ‘b’, ‘d’], required=True)
    

    7. metavar参数:

    表示参数的名字,在显示帮助信息时才用到。

    parser.add_argument(“-o”, metavar=”OOOOOO”)
    

    8. help参数:

    设置这个选项的帮助信息

    9. dest参数:

    设置这个选项的值就是解析出来后放到哪个属性中

    parser.add_argument(“-q”, dest=”world”)
    args = parser.parse_args(args) 
    # 如果你没有args参数,那么就使用sys.argv,也就是命令行参数啦。有这个参数,就方便我们调试啊 。
    # args.world就是-q的值啦
    

    10. const参数:

    常量值,在action和nargs选项用到;

    11. action参数:

    argparse内置6种动作可以在解析到一个参数时进行触发:
    (1)store :保存参数值,可能会先将参数值转换成另一个数据类型。若没有显式指定动作,则默认为该动作。
    (2)store_const: 保存一个被定义为参数规格一部分的值,而不是一个来自参数解析而来的值。这通常用于实现非布尔值的命令行标记。
    (3)store_ture/store_false:保存相应的布尔值,只要有给出对应的参数则对应的布尔型就是true/false。这两个动作被用于实现布尔开关。
    (4)append :将值保存到一个列表中。若参数重复出现,则保存多个值。
    (5)append_const :将一个定义在参数规格中的值保存到一个列表中。
    (6)version :打印关于程序的版本信息,然后退出

    import argparse
    parser = argparse.ArgumentParser()
    
    parser.add_argument('-s', action='store', dest='simple_value',
            help='Store a simple value')
    parser.add_argument('-c', action='store_const', dest='constant_value',
            const='value-to-store',
            help='Store a constant value')
    parser.add_argument('-t', action='store_true', default=False,
            dest='boolean_switch',
            help='Set a switch to true')
    parser.add_argument('-f', action='store_false', default=False,
            dest='boolean_switch',
            help='Set a switch to false')
    parser.add_argument('-a', action='append', dest='collection',
            default=[],
            help='Add repeated values to a list')
    parser.add_argument('-A', action='append_const', dest='const_collection',
            const='value-1-to-append',
            default=[],
            help='Add different values to list')
    parser.add_argument('-B', action='append_const', dest='const_collection',
            const='value-2-to-append',
            help='Add different values to list')
    parser.add_argument('--version', action='version', version='%(prog)s 1.0')
    
    results = parser.parse_args()
    print('simple_value     =', results.simple_value)
    print('constant_value   =', results.constant_value)
    print('boolean_switch   =', results.boolean_switch)
    print('collection       =', results.collection)
    print('const_collection =', results.const_collection)
    
    >>python argparse_action.py -h
    
    usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f]
                              [-a COLLECTION] [-A] [-B] [--version]
    
    optional arguments:
      -h, --help       show this help message and exit
      -s SIMPLE_VALUE  Store a simple value
      -c               Store a constant value
      -t               Set a switch to true
      -f               Set a switch to false
      -a COLLECTION    Add repeated values to a list
      -A               Add different values to list
      -B               Add different values to list
      --version        show program s version number and exit
    
    >>python argparse_action.py -s value
    simple_value     = value
    constant_value   = None
    boolean_switch   = False
    collection       = []
    const_collection = []
    
    >>python argparse_action.py -c
    simple_value     = None
    constant_value   = value-to-store
    boolean_switch   = False
    collection       = []
    const_collection = []
    
    >>python argparse_action.py -t
    simple_value     = None
    constant_value   = None
    boolean_switch   = True
    collection       = []
    const_collection = []
    
    >>python argparse_action.py -f
    simple_value     = None
    constant_value   = None
    boolean_switch   = False
    collection       = []
    const_collection = []
    
    >>python argparse_action.py -a one -a two -a three
    simple_value     = None
    constant_value   = None
    boolean_switch   = False
    collection       = ['one', 'two', 'three']
    const_collection = []
    
    >>python argparse_action.py -B -A
    simple_value     = None
    constant_value   = None
    boolean_switch   = False
    collection       = []
    const_collection = ['value-2-to-append', 'value-1-to-append']
    
    >>python argparse_action.py --version
    argparse_action.py 1.0
    

    四. argparse.ArgumentParser()(可以忽略)

    有以下几种,但是一般我们只选择用description

  • description:命令行帮助的开始文字,大部分情况下,我们只会用到这个参数
  • epilog:命令行帮助的结尾文字
  • prog:(default: sys.argv[0])程序的名字,一般不需要修改,另外,如果你需要在help中使用到程序的名字,可以使用%(prog)s
  • prefix_chars:命令的前缀,默认是-,例如-f/–file。有些程序可能希望支持/f这样的选项,可以使用prefix_chars=”/”
  • fromfile_prefix_chars:(default: None)如果你希望命令行参数可以从文件中读取,就可能用到。
  • add_help:是否增加-h/-help选项 (default: True),一般help信息都是必须的,所以不用设置啦。
  • parents:类型是list,如果这个parser的一些选项跟其他某些parser的选项一样,可以用parents来实现继承,例如parents=[parent_parser]
    三个允许的值:
    (1)class argparse.RawDescriptionHelpFormatter 直接输出description和epilog的原始形式(不进行自动换行和消除空白的操作)
    (2)class argparse.RawTextHelpFormatter 直接输出description和epilog以及add_argument中的help字符串的原始形式(不进行自动换行和消除空白的操作)
    (3)class argparse.ArgumentDefaultsHelpFormatter 在每个选项的帮助信息后面输出他们对应的缺省值,如果有设置的话。
  • argument_default:(default: None)设置一个全局的选项的缺省值,一般每个选项单独设置,所以这个参数用得少,不细说
    usage – (default: generated)如果你需要修改usage的信息(usage: PROG [-h] [–foo [FOO]] bar [bar …]),那么可以修改这个,一般不要修改。
  • conflict_handler – 不建议使用。这个在极端情况下才会用到,主要是定义两个add_argument中添加的选项的名字发生冲突时怎么处理,默认处理是抛出异常。
  • 参考链接:
    https://blog.csdn.net/qq_36653505/article/details/83788460

    物联沃分享整理
    物联沃-IOTWORD物联网 » python3中argparse模块详解

    发表评论