optparse模块主要用来为脚本传递命令参数,采用预先定义好的选项来解析命令行参数。
首先需引入optparser模块 => 然后执行初始化 =>实例化一个OptionParser对象(可以带参,也可以不带参数) =>再为命令行添加选项
官方文档
1 """A powerful, extensible, and easy-to-use option parser. By Greg Ward <gward@python.net> 2 3 Originally distributed as Optik. 4 5 For support, use the optik-users@lists.sourceforge.net mailing list 6 (http://lists.sourceforge.net/lists/listinfo/optik-users). 7 8 Simple usage example: 9 10 from optparse import OptionParser 11 12 parser = OptionParser() 13 parser.add_option("-f", "--file", dest="filename", 14 help="write report to FILE", metavar="FILE") 15 parser.add_option("-q", "--quiet", 16 action="store_false", dest="verbose", default=True, 17 help="don't print status messages to stdout") 18 19 (options, args) = parser.parse_args() 20 """
完整的例子:
1 from optparse import OptionParser 2 [...] 3 def main(): 4 usage = "usage: %prog [options] arg" 5 parser = OptionParser(usage) 6 parser.add_option("-f", "--file", dest="filename", 7 help="read data from FILENAME") 8 parser.add_option("-v", "--verbose", 9 action="store_true", dest="verbose") 10 parser.add_option("-q", "--quiet", 11 action="store_false", dest="verbose") 12 [...] 13 (options, args) = parser.parse_args() 14 if len(args) != 1: 15 parser.error("incorrect number of arguments") 16 if options.verbose: 17 print "reading %s..." % options.filename 18 [...] 19 20 if __name__ == "__main__": 21 main()
[其它参考]
https://www.cnblogs.com/captain_jack/archive/2011/01/11/1933366.html