欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python中的optionParser模块

程序员文章站 2022-05-19 15:18:50
...

 

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