1、optionParser用於處理命令行參數
先看一個例子
#!/usr/bin/python
#coding:utf-8
import sys
import os
import logging
from optparse import OptionParser
DEFAULT_LOG = 'D:/var/log/tcollector.log'
def parse_cmdline(argv):
#獲取默認程序路徑
default_cdir = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
'collectors')
print default_cdir
#獲取相關參數
parser = OptionParser(description='Manages collectors which gather '
'data and report back.')
parser.add_option('-c', '--collector-dir', dest='cdir', metavar='DIR',
default=default_cdir,
help='Directory where the collectors are located.')
parser.add_option('-d', '--dry-run', dest='dryrun', action='store_true',
default=False,
help='Don\'t actually send anything to the TSD, '
'just print the datapoints.')
parser.add_option('-D', '--daemonize', dest='daemonize', action='store_true',
default=False, help='Run as a background daemon.')
parser.add_option('--dedup-interval', dest='dedupinterval', type='int',
default=300, metavar='DEDUPINTERVAL',
help='Number of seconds in which successive duplicate '
'datapoints are suppressed before sending to the TSD. '
'default=%default')
parser.add_option('--evict-interval', dest='evictinterval', type='int',
default=6000, metavar='EVICTINTERVAL',
help='Number of seconds after which to remove cached '
'values of old data points to save memory. '
'default=%default')
parser.add_option('--backup-count', dest='backup_count', type='int',
default=0, help='Maximum number of logfiles to backup.')
(options, args) = parser.parse_args(args=argv[1:])
if options.dedupinterval < 2:
parser.error('--dedup-interval must be at least 2 seconds')
if options.evictinterval <= options.dedupinterval:
parser.error('--evict-interval must be strictly greater than '
'--dedup-interval')
if options.daemonize and not options.backup_count:
options.backup_count = 1
return (options, args)
def main(argv):
#分析參數和選項
options, args = parse_cmdline(argv)
print options
if __name__ == '__main__':
sys.exit(main(sys.argv))
執行結果:
D:\>python ParTest.py --dry-run
D:\collectors
{'dryrun': True, 'evictinterval': 6000, 'daemonize': False, 'dedupinterval': 300
, 'backup_count': 0, 'cdir': 'D:\\collectors'}
2、解釋:
2.1
add_option用來加入選項,action是有store,store_true,store_false等,dest是存儲的變量,default是缺省值,help是幫助提示
最后通過parse_args()函數的解析,獲得選項
2.2
parse_args() 返回的兩個值:
options,它是一個對象(optpars.Values),保存有命令行參數值。只要知道命令行參數名,就可以訪問其對應的值 。
args,它是一個由 positional arguments 組成的列表。
3、optparse 另一個方便的功能是自動生成程序的幫助信息
D:\>python ParTest.py -h
