+#===================================================================
+# class ArgOption : command line option
+#===================================================================
+class ArgOption:
+ """
+ Option class
+ """
+ attrs = ["short_opt", "long_opt", "dest", "action", "type", "default", "metavar", "help"]
+ actions = ["store", "store_true", "store_false"]
+ types = ["string", "int", "float", "bool"]
+ def __init__(self, *args, **kwargs):
+ # set defaults
+ for attr in self.attrs: setattr(self, attr, None)
+ # parse arguments
+ for i in range(len(args)):
+ if i > len(self.attrs)-1:
+ msg = "Wrong number of parameters is given (maximum is %d)" % len(self.attrs)
+ raise OptBaseError(msg)
+ setattr(self, self.attrs[i], args[i])
+ for arg in kwargs:
+ if arg not in self.attrs:
+ msg = "Invalid argument: %s" % arg
+ raise OptBaseError(msg)
+ setattr(self, arg, kwargs[arg])
+ # check short option key
+ if self.short_opt and \
+ not re.match("^-[a-zA-Z]$",self.short_opt):
+ msg = "invalid short option key; "
+ msg += "should be of the form -x (x is letter)"
+ raise OptError(msg, self)
+ # check long option key
+ if self.long_opt and \
+ not re.match("^--[a-zA-Z][a-zA-Z0-9]*(-[a-zA-Z0-9]+)*$",self.long_opt):
+ msg = "invalid long option key; "
+ msg += "should be of the form --word[[-word]...] "
+ msg += "(word is letters and digits sequence)"
+ raise OptError(msg, self)
+ # check that at least one option key is defined
+ if not self.short_opt and not self.long_opt:
+ msg = "invalid option; neither short nor long option key is defined"
+ raise OptError(msg, self)
+ # destination
+ if not self.dest and self.long_opt:
+ self.dest = self.long_opt[2:].replace('-','_')
+ if not self.dest and self.short_opt:
+ self.dest = self.short_opt[1:]
+ # action
+ if not self.action:
+ self.action = "store"
+ if self.action not in self.actions:
+ msg = "invalid action: %s" % self.action
+ raise OptError(msg, self)
+ # type
+ if not self.type:
+ if self.action in ["store_true","store_false"]: self.type = "bool"
+ else: self.type = "string"
+ if self.type not in self.types:
+ msg = "invalid type: %s" % self.type
+ raise OptError(msg, self)
+ if self.action in ["store_true","store_false"] and self.type != "bool":
+ msg = "invalid type: %s : should be 'bool' or None" % self.type
+ raise OptError(msg, self)
+ # default
+ if self.default:
+ try:
+ if self.type == "string": self.default = str(self.default)
+ if self.type == "int": self.default = int(self.default)
+ if self.type == "float": self.default = float(self.default)
+ if self.type == "bool": self.default = boolean(self.default)
+ except :
+ msg = "invalid default value type: should be %s" % self.type
+ raise OptError(msg, self)
+ pass
+ # metavar
+ if not self.metavar:
+ self.metavar = self.dest.upper()
+ # help
+ if not self.help:
+ self.help = ""
+ pass