zoukankan      html  css  js  c++  java
  • Python之argparse

    argparse模块可以轻松编写用户友好的命令行界面。该程序定义了它需要的参数,argparse并将找出如何解析这些参数sys.argvargparse模块还会自动生成帮助和用法消息,并在用户给出程序无效参数时发出错误

    示例

    1.下面的代码是一个 Python 程序,它接受一个整数列表并产生总和或最大值:

    import argparse
    
    parser = argparse.ArgumentParser(description='Process some integers.')  # 创建对象
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
                        help='an integer for the accumulator')  # 添加参数
    parser.add_argument('--sum', dest='accumulate', action='store_const',
                        const=sum, default=max,
                        help='sum the integers (default: find the max)')
    
    args = parser.parse_args()
    print args.accumulate(args.integers)

    假设上面的 Python 代码保存在一个名为的文件中prog.py,它可以在命令行运行并提供有用的帮助信息:

    $ python prog.py -h
    usage: prog.py [-h] [--sum] N [N ...]
    
    Process some integers.
    
    positional arguments:
     N           an integer for the accumulator
    
    optional arguments:
     -h, --help  show this help message and exit
     --sum       sum the integers (default: find the max)

    当使用适当的参数运行时,它会输出命令行整数的总和或最大值:

    $ python prog.py 1 2 3 4
    4
    
    $ python prog.py 1 2 3 4 --sum
    10
  • 相关阅读:
    百度ECharts数据绑定诀窍
    SQL操作Json数据
    c# 如何得到一个字符的ASCII码
    Sql数据库收缩 语句特别快
    Hive中 使用 Round() 的坑
    [转]Hive 数据类型
    [转] Hive函数大全
    使用Hive Rest API 连接HDInsight
    Hive动态分区 参数配置及语法
    Js的引用赋值与传值赋值
  • 原文地址:https://www.cnblogs.com/xingxia/p/python_argparser.html
Copyright © 2011-2022 走看看