zoukankan      html  css  js  c++  java
  • python 中argparse 实例解析

     一 概念:

      argparse是python的一个命令行解析包。它可以使写用户友好的命令行接口变得非常容易。该模块定义什么参数是需要的,并且能指出怎么解析sys.argv的参数。它也可以自动的生成帮助和使用指南。

     二 使用指南:

      1 基本用法:没有参数输入的情况。  

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    parser = argparse.ArgumentParser()
    parser.parse_args()

      根据下面的输出结果可以看出,这样只能默认是-h的输入,别的输入参数就会上报错误。

    $ python base.py 
    $ python base.py -h
    usage: base.py [-h]
    
    optional arguments:
      -h, --help  show this help message and exit
    $ python base.py -v
    usage: base.py [-h]
    base.py: error: unrecognized arguments: -v

      2 参数输入,直接参数可用。

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument("audio")
    args = parser.parse_args()
    print args.audio

      使用方法和结果:

    $ python base.py audio
    audio

      3 可选参数和类型:

      下面的这个参数square 的类型是限定在int类型,-v的类型使用choices限定在[0,1,2],这样就能很方便的看出来该解析函数的使用方法。

    #!/usr/bin/env python
    # encoding: utf-8
    
    
    import argparse
    
    
    parser = argparse.ArgumentParser()
    parser.add_argument("square", type=int,
                                help="display a square of a given number")
    parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2],
                                help="increase output verbosity")
    args = parser.parse_args()
    answer = args.square**2
    if args.verbosity == 2:
            print "the square of {} equals {}".format(args.square, answer)
    elif args.verbosity == 1:
            print "{}^2 == {}".format(args.square, answer)
    else:
            print answer
    ~                        

      使用和运算结果:

    $ python choices_arg.py 4 -v 2
    the square of 4 equals 16
    $ python choices_arg.py -v 2
    usage: choices_arg.py [-h] [-v {0,1,2}] square
    choices_arg.py: error: too few arguments

      通过这几个例子,我们对模块argparse有了大致的了解,详细的使用请参考下面的文档:

    1 https://docs.python.org/3/library/argparse.html

  • 相关阅读:
    CodeForces 7B
    CodeForces 4D
    离散化
    线段树入门
    洛谷 P3951 小凯的疑惑(赛瓦维斯特定理)
    Codeforces 1295D Same GCDs (欧拉函数)
    Codeforces 1295C Obtain The String (二分)
    Codeforces 1295B Infinite Prefixes
    Codeforces 1295A Display The Number(思维)
    Codeforces 1294F Three Paths on a Tree(树的直径,思维)
  • 原文地址:https://www.cnblogs.com/dylancao/p/9963085.html
Copyright © 2011-2022 走看看