python命令行參數模塊argparse
阿新 • • 發佈:2018-01-09
self 信息 host 命令 odin object log message desc 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
python命令行參數模塊argparse