zoukankan      html  css  js  c++  java
  • 33 Python 详解命令解析

    https://blog.csdn.net/lis_12/article/details/54618868

    Python 详解命令行解析 - argparse

    sys.argv

    适合解析简单的命令行

    filename = arg_sys.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    '''
    需要模块:sys
    参数个数:len(sys.argv)
    文件名:    sys.argv[0]
    参数1:     sys.argv[1]
    参数2:     sys.argv[2]
    ......
    '''
    import sys
    print "file = ", sys.argv[0]
    for i in range(1, len(sys.argv)):
        print "parameter%s = %s"%(i, sys.argv[i])
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    在dos输入python arg_sys.py 1 2 3 4 5

    result

    why choice argparse ?

    2.7之后python不再对optparse模块进行扩展,推荐使用argparse模块对命令行进行解析。

    来自stackoverflow的说明

    As of 2.7, optparse is deprecated, and will hopefully go away in the future.

    argparse is better for all the reasons listed on its original page (http://code.google.com/p/argparse/):

    • handling positional arguments
    • supporting sub-commands
    • allowing alternative option prefixes like + and /
    • handling zero-or-more and one-or-more style arguments
    • producing more informative usage messages
    • providing a much simpler interface for custom types and actions

    More information is also in PEP 389, which is the vehicle by which argparse made it into the standard library.

    创建解析器 - ArgumentParser

    import argparse
    parser = argparse.ArgumentParser()
    • 1
    • 2
    class 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)
    • 1

    创建一个ArgumentParser实例,ArgumentParser的参数都为关键字参数。

    prog :文件名,默认为sys.argv[0],用来在help信息中描述程序的名称。

    usage :描述程序用途的字符串

    description :help信息前显示的信息

    epilog :help信息之后显示的信息

    >>> parser = argparse.ArgumentParser(prog='my - program', usage='%(prog)s [options] usage',description = 'my - description',epilog = 'my - epilog')
    >>> parser.print_help()
    usage: my - program [options] usage
    
    my - description
    
    optional arguments:
      -h, --help  show this help message and exit
    
    my - epilog
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    parents :由ArgumentParser对象组成的列表,它们的arguments选项会被包含到新ArgumentParser对象中。(类似于继承)

    formatter_class :help信息输出的格式,为了美观…

    prefix_chars :参数前缀,默认为’-‘(最好不要修改)

    >>> parser = argparse.ArgumentParser(prefix_chars='+')
    >>> parser.add_argument('+x')
    >>> parser.add_argument('++y')
    >>> parser.parse_args('+x 1 ++y 2'.split())
    Namespace(x='1', y='2')
    >>> parser.parse_args('-x 2'.split())
    usage: [+h] [+x X] [++y Y]
    : error: unrecognized arguments: -x 2
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    fromfile_prefix_chars :前缀字符,放在文件名之前

    >>> with open('args.txt', 'w') as fp:
    ...    fp.write('-f
    bar')
    >>> parser = argparse.ArgumentParser(fromfile_prefix_chars='@')
    >>> parser.add_argument('-f')
    >>> parser.parse_args(['-f', 'tmp', '@args.txt'])
    Namespace(f='bar')
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    当参数过多时,可以将参数放到文件中读取,例子中parser.parse_args([‘-f’, ‘foo’, ‘@args.txt’])解析时会从文件args.txt读取,相当于 [‘-f’, ‘foo’, ‘-f’, ‘bar’]

    conflict_handler :解决冲突的策略,默认情况下冲突会发生错误,(最好不要修改)

    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('-f', '--foo', help='old foo help')
    >>> parser.add_argument('--foo', help='new foo help')
    Traceback (most recent call last):
     ..
    ArgumentError: argument --foo: conflicting option string(s): --foo
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    add_help :是否增加-h/-help选项 (默认为True),一般help信息都是必须的。设为False时,help信息里面不再显示-h –help信息

    argument_default: - (default: None)设置一个全局的选项的缺省值,一般每个选项单独设置,基本没用

    添加参数选项 - add_argument

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

    name or flags :参数有两种,可选参数和位置参数。

    1. 添加可选参数

      >>> parser.add_argument('-f', '--foo')
      • 1
    2. 添加位置参数

      >>> parser.add_argument('bar')
      • 1

    parse_args()运行时,默认会用’-‘来认证可选参数,剩下的即为位置参数。

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('name')
    >>> parser.add_argument('-a', '--age')
    >>> parser.parse_args(['xiaoming'])
    Namespace(age=None, name='xiaoming')
    >>> parser.parse_args(['xiaoming','-a','123'])
    Namespace(age='123', name='xiaoming')
    >>> parser.parse_args(['-a','123'])
    usage: [-h] [-a AGE] name
    : error: too few arguments
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    解析时缺少位置参数就会报错了

    action: 默认为store

    1. store_const:值存放在const中:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--foo', action='store_const', const=42)
      >>> parser.parse_args('--foo'.split())
      Namespace(foo=42)
      • 1
      • 2
      • 3
      • 4
    2. store_true和store_false:值存为True或False

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('-x', action='store_true')
      >>> parser.add_argument('-y', action='store_false')
      >>> parser.add_argument('-z', action='store_false')
      >>> parser.parse_args('-x -y'.split())
      Namespace(x=True, y=False, z=True)
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    3. append:存为列表,可以有多个参数

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--l', action='append')
      >>> parser.parse_args('--l 1 --l 2'.split())
      Namespace(l=['1', '2'])
      • 1
      • 2
      • 3
      • 4
    4. append_const:存为列表,会根据const关键参数进行添加:

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--str', dest='types', action='append_const', const=str)
      >>> parser.add_argument('--int', dest='types', action='append_const', const=int)
      >>> parser.parse_args('--str --int --str --int'.split())
      Namespace(l=None, types=[<type 'str'>, <type 'int'>, <type 'str'>, <type 'int'>])
      • 1
      • 2
      • 3
      • 4
      • 5
    5. count:统计参数出现的次数

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--counte', '-c', action='count')
      >>> parser.parse_args('-cccc'.split())
      Namespace(counte=4)
      • 1
      • 2
      • 3
      • 4
    6. help: help信息

    7. version:版本

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('--version', action='version', version='version 2.0')
      >>> parser.parse_args(['--version'])
      version 2.0
      • 1
      • 2
      • 3
      • 4

    metaver:帮助信息中显示的参数名称

    nargs: 参数的数量

    1. 值可以为整数N(N个),*(任意多个,可以为0个),+(一个或更多),有点像正则表达式啊

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('-x', nargs='*')
      >>> parser.add_argument('-y', nargs='*')
      >>> parser.add_argument('-z', nargs='*')
      >>> parser.parse_args('1 2 -x 3 4 -y 5 6'.split())
      Namespace(x=['3', '4'], y=['5', '6'], z=['1', '2'])
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
    2. 值为?时,首先从命令行获得参数,如果有-y后面没加参数,则从const中取值,如果没有-y,则从default中取值

      >>> parser = argparse.ArgumentParser()
      >>> parser.add_argument('x', nargs='?',default='default')
      >>> parser.add_argument('-y', nargs='?',const='const', default='default')
      >>> parser.parse_args('1 -y 2'.split())
      Namespace(x='1', y='2')
      >>> parser.parse_args('1 -y'.split())
      Namespace(x='1', y='const')
      >>> parser.parse_args([])
      Namespace(x='default', y='default')
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9

    const :保存一个常量

    default :默认值

    type :参数类型,默认为str

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

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('x', type=int, choices=range(1, 4))
    >>> parser.parse_args(['3'])
    Namespace(x=3)
    >>> parser.parse_args(['4'])
    usage: [-h] {1,2,3}
    : error: argument x: invalid choice: 4 (choose from 1, 2, 3)
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    required :该选项是否必选,默认为True

    dest :参数名

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo', dest='f_name')
    >>> parser.parse_args('--foo XXX'.split())
    Namespace(f_name='XXX')
    • 1
    • 2
    • 3
    • 4

    解析参数

    像名称空间一样使用即可

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('x')
    >>> a = parser.parse_args(['1'])
    >>> a
    Namespace(x='1')
    >>> type(a)
    <class 'argparse.Namespace'>
    >>> a.x
    '1'
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    example

    filename = argv_argparse.py

    #!/usr/bin/python
    # -*- coding: utf-8 -*-
    import sys
    import argparse
    
    def cmd():
        args = argparse.ArgumentParser(description = 'Personal Information ',epilog = 'Information end ')
        #必写属性,第一位
        args.add_argument("name",         type = str,                  help = "Your name")
        #必写属性,第二位
        args.add_argument("birth",        type = str,                  help = "birthday")
        #可选属性,默认为None
        args.add_argument("-r",'--race',  type = str, dest = "race",   help = u"民族")
        #可选属性,默认为0,范围必须在0~150
        args.add_argument("-a", "--age",  type = int, dest = "age",    help = "Your age",         default = 0,      choices=range(150))
        #可选属性,默认为male
        args.add_argument('-g',"--gender",   type = str, dest = "gender",    help = 'Your gender',         default = 'male', choices=['male', 'female'])
        #可选属性,默认为None,-p后可接多个参数
        args.add_argument("-p","--parent",type = str, dest = 'parent', help = "Your parent",      default = "None", nargs = '*')
        #可选属性,默认为None,-o后可接多个参数
        args.add_argument("-o","--other", type = str, dest = 'other',  help = "other Information",required = False,nargs = '*')
    
        args = args.parse_args()#返回一个命名空间,如果想要使用变量,可用args.attr
        print "argparse.args=",args,type(args)
        print 'name = %s'%args.name
        d = args.__dict__
        for key,value in d.iteritems():
            print '%s = %s'%(key,value)
    
    if __name__=="__main__":
        cmd()
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    dos输入命令示例:

    python argv_argparse.py -h

    python argv_argparse.py xiaoming 1991.11.11

    python argv_argparse.py xiaoming 1991.11.11 -p xiaohong xiaohei -a 25 -r han -g female -o 1 2 3 4 5 6


    转载请标明出处,原文地址(http://blog.csdn.net/lis_12/article/details/54618868).

    如果觉得本文对您有帮助,请点击支持一下,您的支持是我写作最大的动力,谢谢。

    参考网址

    1. https://docs.python.org/2/library/argparse.html#module-argparse
    2. http://www.jb51.net/article/67158.htm
    3. http://stackoverflow.com/questions/3217673/why-use-argparse-rather-than-optparse
    4. http://www.cnblogs.com/linxiyue/p/3908623.html?utm_source=tuicool&utm_medium=referral
  • 相关阅读:
    June 26th 2017 Week 26th Monday
    June 25th 2017 Week 26th Sunday
    June 24th 2017 Week 25th Saturday
    June 23rd 2017 Week 25th Friday
    June 22nd 2017 Week 25th Thursday
    2018最佳网页设计:就是要你灵感爆棚!!!
    图片素材类Web原型制作分享-Pexels
    想要打动HR的心,UX设计师求职信究竟应该怎么写?
    【UXPA大赛企业专访】Mockplus:“设计替代开发”将成为现实
    2018年最好的医疗网站设计及配色赏析
  • 原文地址:https://www.cnblogs.com/nkwy2012/p/9081337.html
Copyright © 2011-2022 走看看