argparse

说明

  • 处理可选参数与位置参数
  • handles both optional and positional arguments
  • 产生标准化的帮助信息
  • produces highly informative usage messages
  • 支持调度子分器的解析器
  • supports parsers that dispatch to sub-parsers

Example code

    # 初始化一个实例
    parser = argparse.ArgumentParser(
        description='sum the integers at the command line')
    
    # 添加位置参数, 类型为int    
    parser.add_argument(
        'integers', metavar='int', nargs='+', type=int,
        help='an integer to be summed')
    
    # 添加可选参数,默认为标准输出,类型为FileType文件类    
    parser.add_argument(
        '--log', default=sys.stdout, type=argparse.FileType('w'),
        help='the file where the sum should be written')
    
    # 解析    
    args = parser.parse_args()
    # Namespace(count='50', echo='good', host='172.168.100.1')
    
    args.log.write('%s' % sum(args.integers))
    args.log.close()

Example code

#coding:utf8

import argparse

class Args(object):

    def __init__(self):
        parser = argparse.ArgumentParser(
            description="A test network port tool"
        )
        parser.add_argument(
            "echo",
            help="echo info."
        )
        parser.add_argument(
            "-H", "--host",
            help="ipaddr or domain addr."
        )
        parser.add_argument(
            "-c", "--count",
            help="connect counts"
        )
        args = parser.parse_args()
        self.args = args

    def cc(self):
        print self.args
        print "args host: ", self.args.host
        print "args count: " ,self.args.count

if __name__ == "__main__":
    a = Args()
    a.cc()

Result

➜  test git:(master) ✗ python argpar.py good -H 172.168.100.1 -c 50
Namespace(count='50', echo='good', host='172.168.100.1')
args host:  172.168.100.1
args count:  50