python 使用optparse解析命令行选项

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用optparse解析命令行选项相关的知识,希望对你有一定的参考价值。

#!/usr/bin/python
# -*- coding: utf-8 -*-

from optparse import OptionParser 
## parser.add_option('<short-hand>', "<long-hand>", dest = <binding attribute>, type=<type>, action=<action>, default=<default_value> )
## four most important option attributes:
# action("store"(default), 'store_false/true' (setting boolean flag), 'store_const', 'append' (append this opt's arg to a list), 'callback' (invoke a callback function) ), 
# type ("string","int",'float',... )
# dest (the attribute name of parsed options object)
# help (help string for this option)
# If you don’t supply a destination, optparse figures out a sensible default from the option strings: 
# if the first long option string is --foo-bar, then the default destination is foo_bar.
# If there are no long option strings, optparse looks at the first short option string: the default destination for -f is f.
# 
# Default values for options can be set by default parameter for each add_option() call 
# use OptionParser.error(<msg>) to raise user-input errors 
def clitool():
    usage = "USAGE: %prog [options] arg1 arg2" 
    parser = OptionParser(usage=usage)
    # parser.set_defaults(<flag>=<default>...)

    parser.add_option("-f","--file" )

def sample_command():
    usage = "usage: %prog [options] arg"
    parser = OptionParser(usage)
    parser.add_option("-f", "--file", dest="filename",
                      help="read data from FILENAME")
    parser.add_option("-v", "--verbose",
                      action="store_true", dest="verbose")
    parser.add_option("-q", "--quiet",
                      action="store_false", dest="verbose")
    ...
    (options, args) = parser.parse_args()
    if len(args) != 1:
        parser.error("incorrect number of arguments")
    if options.verbose:
        print "reading %s..." % options.filename
    # ... all the logic to deal with options and args

if __name__ == "__main__":
    main()

以上是关于python 使用optparse解析命令行选项的主要内容,如果未能解决你的问题,请参考以下文章

python OptParse模块的用法详解

Python 命令行参数解析: optparse 模块

python中optparse模块用法

从命令行选项创建一个数组 (python::optparse)

python学习笔记14-optparse真正的命令行参数

python模块-optparse(解析命令行参数)