/ Published in: Python
Snippet to show how works optparse module to add optoins when it is called by command line
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
#!/usr/bin/python #-*- coding:utf-8 -*- from optparse import OptionParser class Options: def __init__(self, args): self.opt_parser = OptionParser() # this option create a boolean variable, that default is False # and if you call with -m param it will be True self.opt_parser.add_option( "-m", "--mouse_visible", dest="mouse_visible", action="store_true", default=False ) # option that create a integer variable, defaultsv value is # 0 and when is passed it store the option value: # my_command -v 32 # that stores 32 self.opt_parser.add_option( "-v", "--necesary_value", dest="necesary_value", action="store", type="int", default=0 ) # parse args in array passed as param in __init__ method (self.options, args) = self.opt_parser.parse_args(args) def get_mouse_visible(self): ''' ''' return self.options.mouse_visible def get_necesary_value(self): ''' ''' return self.options.necesary_value if __name__ == "__main__": # options passed by commnand are inicializated opt = Options (sys.argv) print "Mouse is visible? %s" % opt.get_mouse_visible() print "Value needed: %s" %opt.get_necesary_value()