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

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

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

    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()
    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)

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

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

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

    description :help信息前显示的信息

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

    >>> import argparse
    >>> parser = argparse.ArgumentParser(prog='my - program', usage='%(prog)s [optio
    ns] 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

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

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

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

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

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

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

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

    action: 默认为store

    nargs: 参数的数量

    const :保存一个常量

    default :默认值

    type :参数类型,默认为str

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

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

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

    dest :参数名

    >>> import argparse
    >>> parser=argparse.ArgumentParser()
    >>> parser.add_argument('--version', action='version', version='version 2.0')
    _VersionAction(option_strings=['--version'], dest='version', nargs=0, const=None
    , default='==SUPPRESS==', type=None, choices=None, help="show program's version
    number and exit", metavar=None)
    >>> parser.parse_args(['--version'])
    version 2.0

    例子:

    import argparse

    def parse_arguments(version_info, args=None):
    parser = argparse.ArgumentParser()

    parser.add_argument('-v', '--version', action='version',
    version=version_info,
    help='Show program version info and exit.')

    parser.parse_args(args)
    if __name__ == "__main__":

    parse_arguments("${version_info}")

    参考网址:

    原文地址(http://blog.csdn.net/lis_12/article/details/54618868).

  • 相关阅读:
    postgreSQL入门命令
    JDBC连接数据库
    nano编辑器使用教程
    Linux上vi(vim)编辑器使用教程
    【编程思想】【设计模式】【行为模式Behavioral】状态模式State
    【编程思想】【设计模式】【行为模式Behavioral】Specification
    【编程思想】【设计模式】【行为模式Behavioral】registry
    【编程思想】【设计模式】【行为模式Behavioral】Publish_Subscribe
    【编程思想】【设计模式】【行为模式Behavioral】观察者模式Observer
    【编程思想】【设计模式】【行为模式Behavioral】备忘录模式Memento
  • 原文地址:https://www.cnblogs.com/skyer/p/6344111.html
Copyright © 2011-2022 走看看