3 # Copyright (C) 2010-2013 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 '''The Options class that manages the access to all options passed as
19 parameters in salomeTools command lines
23 from . import printcolors
25 class OptResult(object):
26 '''An instance of this class will be the object manipulated
27 in code of all salomeTools commands
28 The aim of this class is to have an elegant syntax
29 to manipulate the options.
37 self.__dict__ = dict()
39 def __getattr__(self, name):
40 '''Overwrite of the __getattr__ function
41 to customize it for option usage
43 :param name str: The attribute to get the value.
44 :return: the value corresponding to the attribute.
45 :rtype: str,int,list,boolean
47 if name in self.__dict__:
48 return self.__dict__[name]
50 raise AttributeError(name + _(u" is not a valid option"))
52 def __setattr__(self, name, value):
53 '''Overwrite of the __setattr__ function
54 to customize it for option usage
56 :param name str: The attribute to set.
57 :param value str: The value corresponding to the attribute.
61 object.__setattr__(self,name,value)
64 '''Class to manage all salomeTools options
69 # The options field stocks all options of a command
70 # in a list that contains dicts
72 # The list of available option type
73 self.availableOptions = ["boolean", "string", "int", "float",
74 "long", "list", "list2"]
77 def add_option(self, shortName, longName,
78 optionType, destName, helpString="", default = None):
79 '''Method to add an option to a command. It gets all attributes
80 of an option and append it in the options field
82 :param shortName str: The short name of the option
83 (ex "l" for level option).
84 :param longName str: The long name of the option
85 (ex "level" for level option).
86 :param optionType str: The type of the option (ex "int").
87 :param destName str: The name that will be used in the code.
88 :param helpString str: The text to display
89 when user ask for help on a command.
94 option['shortName'] = shortName
95 option['longName'] = longName
97 if optionType not in self.availableOptions:
98 print("error optionType", optionType, "not available.")
101 option['optionType'] = optionType
102 option['destName'] = destName
103 option['helpString'] = helpString
104 option['result'] = default
105 self.options.append(option)
107 def print_help(self):
108 '''Method that display all options stored in self.options and there help
113 # Do nothing if there are no options
114 if len(self.options) == 0:
117 # for all options, print its values.
118 # "shortname" is an optional field of the options
119 print(printcolors.printcHeader(_("Available options are:")))
120 for option in self.options:
121 if 'shortName' in option and len(option['shortName']) > 0:
122 print(" -%(shortName)1s, --%(longName)s"
123 " (%(optionType)s)\n\t%(helpString)s\n" % option)
125 print(" --%(longName)s (%(optionType)s)\n\t%(helpString)s\n"
128 def parse_args(self, argList=None):
129 '''Method that instantiates the class OptResult
130 that gives access to all options in the code
132 :param argList list: the raw list of arguments that were passed
133 :return: optResult, args : optResult is the option instance
134 to manipulate in the code. args
135 is the full raw list of passed options
136 :rtype: (class 'common.options.OptResult',list)
139 argList = sys.argv[1:]
141 # format shortNameOption and longNameOption
142 # to make right arguments to getopt.getopt function
145 for option in self.options:
146 shortNameOption = shortNameOption + option['shortName']
147 if option['shortName'] != "" and option['optionType'] != "boolean":
148 shortNameOption = shortNameOption + ":"
150 if option['longName'] != "":
151 if option['optionType'] != "boolean":
152 longNameOption.append(option['longName'] + "=")
154 longNameOption.append(option['longName'])
156 # call to getopt.getopt function to get the option
157 # passed in the command regarding the available options
158 optlist, args = getopt.getopt(argList, shortNameOption, longNameOption)
160 # instantiate and completing the optResult that will be returned
161 optResult = OptResult()
162 for option in self.options:
163 shortOption = "-" + option['shortName']
164 longOption = "--" + option['longName']
165 optionType = option['optionType']
167 if opt[0] in [shortOption, longOption]:
168 if optionType == "string":
169 option['result'] = opt[1]
170 elif optionType == "boolean":
171 option['result'] = True
172 elif optionType == "int":
173 option['result'] = int(opt[1])
174 elif optionType == "float":
175 option['result'] = float(opt[1])
176 elif optionType == "long":
177 option['result'] = long(opt[1])
178 elif optionType == "list":
179 if option['result'] is None:
180 option['result'] = list()
181 option['result'].append(opt[1])
182 elif optionType == "list2":
183 if option['result'] is None:
184 option['result'] = list()
185 if opt[1].find(",") == -1:
186 option['result'].append(opt[1])
188 elts = filter(lambda l: len(l) > 0, opt[1].split(","))
189 option['result'].extend(elts)
191 optResult.__setattr__(option['destName'], option['result'])
192 # free the option in order to be able to make
193 # a new free call of options (API case)
194 option['result'] = None
195 return optResult, args