Optparse 简介

optparse 这个库的主要作用是可以用为脚本提供传递命令参数功能

一个简单的例子

def main():
    parser = OptionParser(usage = "usage: %prog [option] arg1")
    parser.add_option("-s","--startdate",
                     action = "store",type= "string",dest = 'StartDate',default = "Latest",
                     help = "Type the StartDate, otherwise it will be the Latest Date of What You Have in Your Computer",)
    print(parser.StartDate)                 
If __name__ == '__main__':
    main()                     

假设改脚本的名字为A.py, 然后你可以进入命令行,输入

python A.py -s 20170504

你会得到

20170504

简单介绍一下parser.add_option()的参数

action: 指示optparse解析一个命令行参数时该如何处理。简单的来说,就是如果命令行如果传递了参数,我们该怎么办。常见的参数有 store, store_true, store_false. store 是把你输入的参数存放到options对象里,store_true 和 store_false 是配合使用的,类似于boolean变量,如果你触发了store_true, 该命令对应的对象则为1, 反之则为0。

dest: dest可以调用你存进option对象的参数。用上面的例子,如果你输入上面的命令行命令,则会打印出20170504,这里起作用的是这一行

print(parser.dest)

也就是说,你输入的参数可以用dest来调用

default: default 是当你没有输入参数是,仅仅输入了-s,这里

parser.StartDate = 'Latest'

help: 是用来说明改命令是用来干什么,提供解释

parser.error() 用来报错
当然你也可以用sys.exit()

范例代码

import optparserparser
from optparser import OptionParser

def main():
    parser = OptionParser(usage = "usage: %prog [option] arg1")
    parser.add_option("-s","--startdate",
                     action = "store",type= "string",dest = 'StartDate',default = "Latest",
                     help = "Type the StartDate, otherwise it will be the Latest Date of What You Have in Your Computer",)
    parser.add_option("-e","--enddate",
                     action = "store",type= "string",dest = 'EndDate', default = "Today",
                     help = "Type the EndDate, otherwise it will be Today",)
    parser.add_option("-f","--from",
                     action = "store",type = "string",dest = "UserID",
                     help = "Website",)
    parser.add_option("-t","--to",
                     action = "store",type = "string",dest = "SaveAddress",default = "C:/Users/kinsly/Work",
                     help = "Type the Address you want to save",)
   
    (option,args) = parser.parse_args()
    if not options.UserID:
        parser.error('ID is not given')
    
if __name__ == '__main__':
    main()

reference:

  1. Python: How to make an option to be required in optparse?
    https://stackoverflow.com/questions/4407539/python-how-to-make-an-option-to-be-required-in-optparse
  2. Python模块学习——使用 optparse 处理命令行参数
    http://shelly-kuang.iteye.com/blog/797713
  3. optparse — Parser for command line options
    https://docs.python.org/3/library/optparse.html
  4. Python optparser库详解
    http://blog.csdn.net/marksinoberg/article/details/51842197

posted on 2017-07-14 22:28  kinsly  阅读(640)  评论(0编辑  收藏  举报

导航