Return to Snippet

Revision: 61124
at November 29, 2012 21:55 by ssoton


Updated Code
#!/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()

Revision: 61123
at November 29, 2012 21:53 by ssoton


Initial Code
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()

Initial URL
python_parser_options

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

Initial Title
Python main with options

Initial Tags
python

Initial Language
Python