zoukankan      html  css  js  c++  java
  • [Python] Argparse module

    he recommended command-line parsing module in the Python standard library

    1. Basic

    import argparse
    
    parser = argparse.ArgumentParser()
    parser.parse_args()
    

      

    $ python prog.py --help
    usage: prog.py [-h]
    
    optional arguments:
      -h, --help  show this help message and exit
    

      

    display the usefulness of the argparse module

    2. positional argument

    eg

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("echo")
    args = parser.parse_args()
    print args.echo
    

      

    result

    $ python prog.py
    usage: prog.py [-h] echo
    prog.py: error: the following arguments are required: echo
    $ python prog.py --help
    usage: prog.py [-h] echo
    
    positional arguments:
      echo
    
    optional arguments:
      -h, --help  show this help message and exit
    $ python prog.py foo
    foo
    

      

    If we want to change the argument into an integer, we can:

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("square", help="display a square of a given number",
                        type=int)
    args = parser.parse_args()
    print args.square**2
    

      

    3. optional argument

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("--verbosity", help="increase output verbosity")
    args = parser.parse_args()
    if args.verbosity:
        print "verbosity turned on"
    

      

    output

    $ python prog.py --verbosity 1
    verbosity turned on
    $ python prog.py
    $ python prog.py --help
    usage: prog.py [-h] [--verbosity VERBOSITY]
    
    optional arguments:
      -h, --help            show this help message and exit
      --verbosity VERBOSITY
                            increase output verbosity
    $ python prog.py --verbosity
    usage: prog.py [-h] [--verbosity VERBOSITY]
    prog.py: error: argument --verbosity: expected one argument
    

      

    4. short option

    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--verbose", help="increase output verbosity",
                        action="store_true")
    args = parser.parse_args()
    if args.verbose:
        print "verbosity turned on"
    

      

    output

    $ python prog.py -v
    verbosity turned on
    $ python prog.py --help
    usage: prog.py [-h] [-v]
    
    optional arguments:
      -h, --help     show this help message and exit
      -v, --verbose  increase output verbosity
    

      

  • 相关阅读:
    vue中使用keepAlive(缓存页面&记忆上次浏览位置)及使用后生命周期的改变
    vue搭配antD-Vue开发项目(一)
    vscode使用
    vue移动端项目经验(三)
    [CF960F] Pathwalks
    [CF1004E] Sonya and Ice-cream
    [CF1142B] Lynyrd Skynyrd
    [CF55D] Beautiful numbers
    [洛谷P4438] HNOI2018 道路
    JOI2019 有趣的家庭菜园3
  • 原文地址:https://www.cnblogs.com/KennyRom/p/6354123.html
Copyright © 2011-2022 走看看