zoukankan      html  css  js  c++  java
  • python之命令行解析工具argparse

    以前写python的时候都会自己在文件开头写一个usgae函数,用来加上各种注释,给用这个脚本的人提供帮助文档。

    今天才知道原来python已经有一个自带的命令行解析工具argparse,用了一下,效果还不错。

    argparse的官方文档请看 https://docs.python.org/2/howto/argparse.html#id1

    from argparse import ArgumentParser
    
    p = ArgumentParser(usage='it is usage tip', description='this is a test')
    p.add_argument('--one', default=1, type=int,  help='the first argument')
    args = p.parse_args()
    print args

    运行这个脚本test.py.

    python test.py -h

    输出:

    usage: it is usage tip

    this is a test

    optional arguments:
      -h, --help  show this help message and exit
      --one ONE   the first argument

    python test.py --one  8

     输出:

     Namespace(one=8)

    可以看到argparse自动给程序加上了-h的选项,最后p.parse_args()得到的是你运行脚本时输入的参数。

    如果我们需要用这些参数要怎么办呢,可以通过vars()转换把Namespace转换成dict。

    from argparse import ArgumentParser
    
    p = ArgumentParser(usage='it is usage tip', description='this is a test')
    p.add_argument('--one', default=1, type=int,  help='the first argument')
    p.add_argument('--two', default='hello', type=str, help='the second argument')
    
    args = p.parse_args()
    print args
    mydict = vars(args)
    print mydict
    print mydict['two']

    运行test.py.

    python test.py --one 8  --two good

    输出:

    Namespace(one=8, two='good')
    {'two': 'good', 'one': 8}
    good

  • 相关阅读:
    动手动脑篇之类与对象
    团队精神
    在快乐中学习
    实习报告
    大道至简读后感(二)
    大道至简读后感
    读《大道至简》第一章有感
    指令随笔之:tail、cat、scp、&、&&、;、|、>、>>
    NFS安装过程
    CentOS7编译安装Nginx-1.8.1和编译参数
  • 原文地址:https://www.cnblogs.com/streakingBird/p/3928756.html
Copyright © 2011-2022 走看看