zoukankan      html  css  js  c++  java
  • 详解Python中argpasrse模块的基本使用

    argpasrse模块的使用

    import  argparse
    parser = argparse.ArgumentParser(
        prog = 'ls',
        description='Process some int',
        add_help = True
    )
    parser.add_argument('path',nargs='?', default='.', help='file path')# 位置参数
    parser.add_argument('-l',dest='list', action='store_true')
    parser.add_argument('-a', '--all', action='store_true')
    
    
    args = parser.parse_args() # 解析:如:/etc ---> e t c  把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)
    parser.print_help() # windows  使用这个调试
    print('-------------------------------------')
    print( args.all, args.list, args.path) #None None /etc
    

    在win下,模拟插入位置参数,如 /etc 可以在run-->Edit configuration下或者在:args = parser.parse_args('/etc')

    ① 默认会打印帮助信息,默认提供 '''

    py文件:

    
    import  argparse
    parser = argparse.ArgumentParser(description='Process some int')
    args = parser.parse_args()
    parser.print_help() # windows  使用这个调试
    

    打印信息:

    usage: homework_解析_9-4.py [-h]
    
    Process some int
    
    optional arguments:
      -h, --help  show this help message and exit
    

    ② ArgumentParser下的内容

    def __init__(self,
                     prog=None,描述程序的,sys.args[0]也就是输入的命令, 如:a.py
                     usage=None,程序使用方式
                     description=None,
                     epilog=None,
                     parents=[],
                     formatter_class=HelpFormatter,
                     prefix_chars='-',
                     fromfile_prefix_chars=None,
                     argument_default=None, 缺省值
                     conflict_handler='error',
                     add_help=True,默认的帮助信息,-h,--help Fals表示取消
                     allow_abbrev=True):
    

    ③ 取消help

    
    import  argparse
    parser = argparse.ArgumentParser(
        prog = 'ls',  # 给命令起个名字 ls
        description='Process some int',
        add_help = False # 改为False
    )
    args = parser.parse_args()
    parser.print_help() # windows  使用这个调试
    

    打印信息:

    usage: ls
    
    Process some int
    

    没有取消的信息:

    usage: ls [-h] # 中括号表示可选,linux特色
    
    Process some int
    
    optional arguments:
      -h, --help  show this help message and exit
    

    ④ 必须提供参数,也就是说执行ls.py的时候,后面要跟 路径 如:/etc

    
    import  argparse
    parser = argparse.ArgumentParser(
        prog = 'ls',
        description='Process some int',
        add_help = True
    )
    parser.add_argument('path')# 
    

    打印信息

    args = parser.parse_args()
    usage: ls [-h] path
    ls: error: the following arguments are required: path
    

    ⑤ 长选项

    import  argparse
    parser = argparse.ArgumentParser(
        prog = 'ls',
        description='Process some int',
        add_help = True
    )
    parser.add_argument('path')
    parser.add_argument('-l')
    parser.add_argument('-a','--all')
    
    args = parser.parse_args()
    

    打印信息:

    usage: ls [-h] [-l L] [-a ALL] path
    
    Process some int
    
    positional arguments:
      path
    
    optional arguments:
      -h, --help         show this help message and exit
      -l L
      -a ALL, --all ALL
    

    ⑥ namespace,sys.argv[1:],没有提供 ,就是None,提供了,则传到namespace

    import  argparse
    parser = argparse.ArgumentParser(
        prog = 'ls',
        description='Process some int',
        add_help = True
    )
    parser.add_argument('path')
    parser.add_argument('-l')
    parser.add_argument('-a','--all')
    
    args = parser.parse_args(('/etc',)) # 解析:如:/etc ---> e t c  把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)
    parser.print_help() # windows  使用这个调试
    print(args)
    

    打印信息:

    usage: ls [-h] [-l L] [-a ALL] path
    
    Process some int
    
    positional arguments:
      path
    
    optional arguments:
      -h, --help         show this help message and exit
      -l L
      -a ALL, --all ALL
    Namespace(all=None, l=None, path='/etc')!!!!!!!!!!!!!!!!!!
    

    ⑦ 获取参数对应的属性的值 ,通过namespace,但是参数如果有--all这样的,只能用args.all'''

    args = parser.parse_args('/etc'.split()) # 解析:如:/etc ---> e t c  把其当作一个可迭代对象了,所以可以这样输入 ('/etc',)
    print( args.all, args.l, args.path) #None None /etc
    

    打印信息:

    None None /etc
    

    ⑧ -l -a 默认必须带参,如何不带参'''

    帮助文档:

        add_argument() method
             •name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
             •action - The basic type of action to be taken when this argument is encountered at the command line.
             •nargs - The number of command-line arguments that should be consumed.
             •const - A constant value required by some action and nargs selections.
             •default - The value produced if the argument is absent from the command line.
             •type - The type to which the command-line argument should be converted.
             •choices - A container of the allowable values for the argument.
             •required - Whether or not the command-line option may be omitted (optionals only).
             •help - A brief description of what the argument does.
             •dest - The name of the attribute to be added to the object returned by parse_args().
    parser.add_argument('path',nargs='?')# 位置参数
    打印:
        usage: ls [-h] [-l L] [-a ALL] [path] 此时path 加中括号了,可有可无
    
    parser.add_argument('path',nargs='?', default='.')# 位置参数,加了一个默认值,当前目录
    
    #### ? 表示可有可无,+ 至少一个,*可以任意个,数字表示必须指定数目
    
    parser.add_argument('-l', action='store_true') # 不需要传参了
    

    打印信息:

        usage: ls [-h] [-l] [-a ALL] [path]  
        
     
        
    parser.add_argument('-l', action='store_true')
    args = parser.parse_args('-l'.split()) 
    print( args.all, args.l, args.path) 
    

    打印信息:
    因为store_true,所以给了 -l 则打印true,否则为 false
    如果store_false,不给-l 就打印true

    parser.add_argument('-l', action='store_const', const=23)
    args = parser.parse_args('-l'.split()) 
    

    打印信息:
    如果给了,就打印 23,不给,打印None

    ⑨ 每个命令提供一个help信息 '''

    parser.add_argument('path',nargs='?', default='.', help='file path')# 位置参数
    

    打印信息:

      path        file path
    

    ⑩ 给namespace的属性提供一个方便使用的名字,如args.l 使用args.list'''

    parser.add_argument('-l',dest='list', action='store_true')
    print( args.all, args.list, args.path) #None None /etc
    

    打印信息:

    False False . 
    

    这个名字只是在namespace中用,不会影响命令调用时的 -l

  • 相关阅读:
    leetcode 75 颜色分类 A
    leetcode525连续数组 A
    WCF无身份验证配置
    三读设计模式
    EntityFrameWork+Oracle学习笔记搭配环境(一)
    EntityFrameWork+Oracle学习笔记DBfirst(二)
    用Python解答百度测试开发算法面试题
    Python实现采集wordpress整站数据的爬虫
    吾八哥学Python(六):运算符与表达式
    吾八哥学Python(四):了解Python基础语法(下)
  • 原文地址:https://www.cnblogs.com/python960410445/p/12569850.html
Copyright © 2011-2022 走看看