Python main with options


/ Published in: Python
Save to your folder(s)

Snippet to show how works optparse module to add optoins when it is called by command line


Copy this code and paste it in your HTML
  1. #!/usr/bin/python
  2. #-*- coding:utf-8 -*-
  3.  
  4. from optparse import OptionParser
  5.  
  6. class Options:
  7.  
  8. def __init__(self, args):
  9. self.opt_parser = OptionParser()
  10. # this option create a boolean variable, that default is False
  11. # and if you call with -m param it will be True
  12. self.opt_parser.add_option( "-m",
  13. "--mouse_visible",
  14. dest="mouse_visible",
  15. action="store_true",
  16. default=False
  17. )
  18. # option that create a integer variable, defaultsv value is
  19. # 0 and when is passed it store the option value:
  20. # my_command -v 32
  21. # that stores 32
  22. self.opt_parser.add_option( "-v",
  23. "--necesary_value",
  24. dest="necesary_value",
  25. action="store",
  26. type="int",
  27. default=0
  28. )
  29. # parse args in array passed as param in __init__ method
  30. (self.options, args) = self.opt_parser.parse_args(args)
  31.  
  32. def get_mouse_visible(self):
  33. ''' '''
  34. return self.options.mouse_visible
  35.  
  36. def get_necesary_value(self):
  37. ''' '''
  38. return self.options.necesary_value
  39.  
  40.  
  41. if __name__ == "__main__":
  42. # options passed by commnand are inicializated
  43. opt = Options (sys.argv)
  44. print "Mouse is visible? %s" % opt.get_mouse_visible()
  45. print "Value needed: %s" %opt.get_necesary_value()

URL: python_parser_options

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.