1
2 """
3 Groups of options set on the command line.
4 """
5 VERBOSE = False
6
8 """
9 Any error related to OptionsGroup
10 """
11 pass
12
14 """
15 Its attributes are the its option names and values.
16 """
18 """
19 Sets a value of an option.
20
21 If value is a string, it will be casted to the type of the option
22 to be set. If the option is a tuple of 4 floats, for example, it
23 will be expected to in the form "1.0,0.8,0.2,1.0" where "," is the
24 separator.
25
26 :param option_name: Name of the attribute
27 :param value: Either a string, or any Python type.
28 """
29 key = option_name
30 if not hasattr(self, option_name):
31 raise OptionsError("No no option named %s in options group" % (key))
32 else:
33 attr = getattr(self, key)
34 attr_type = type(attr)
35 if attr_type in [int, float, str]:
36 try:
37 setattr(self, key, attr_type(value))
38 except ValueError, e:
39 raise OptionsError("Could not convert value %s to type %s for option %s. %s" % (value, attr_type.__name__, key, e.message))
40 elif attr_type is list:
41 tuple_length = len(attr)
42 if type(value) is str:
43 elements = value.split(",")
44 else:
45 elements = value
46 if len(elements) != tuple_length:
47 raise OptionsError("Option %s should have %s elements but has %s." % (key, tuple_length, len(elements)))
48 else:
49 for i in range(len(elements)):
50 element_type = type(attr[i])
51 try:
52 attr[i] = element_type(elements[i])
53 except ValueError, e:
54 raise OptionsError("Could not convert element %s (%s) to type %s for option %s. %s" % (i, elements[i], element_type.__name__, key, e.message))
55 else:
56 raise OptionsError("Impossible to convert option %s of group %s to type %s." % (key, group, attr_type))
57
58 if __name__ == "__main__":
61 self.i = 3
62 self.f = 2.0
63 self.s = "qwe"
64 self.t4 = [1.0, 0.8, 0.2, 1.0]
65 self.t3 = [1.0, 0.8, 0.2]
66 import optparse
67 VERSION = '0.1'
68 parser = optparse.OptionParser(usage="%prog", version=VERSION)
69 parser.add_option("-x", "--effect-option",
70 action="append", nargs=3,
71 help="Sets effect option")
72 (options, args) = parser.parse_args()
73 groups = {}
74 groups["ex"] = ExampleGroup()
75 print("Before:")
76 for name, group in groups.items():
77 print(" %s: %s" % (name, group.__dict__))
78 print("effect_option: %s" % (options.effect_option))
79 if options.effect_option is not None:
80 for group, key, value in options.effect_option:
81
82
83 if group not in groups.keys():
84 print("No group named %s." % (group))
85 else:
86 obj = groups[group]
87 obj.set_value(key, value)
88
89 print("After:")
90 for name, group in groups.items():
91 print("%s: %s" % (name, group.__dict__))
92