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 parameters in salomeTools command lines
22 from . import printcolors
24 class OptResult(object):
25 '''An instance of this class will be the object manipulated in code of all salomeTools commands
26 The aim of this class is to have an elegant syntax to manipulate the options.
34 self.__dict__ = dict()
36 def __getattr__(self, name):
37 '''Overwrite of the __getattr__ function to customize it for option usage
39 :param name str: The attribute to get the value.
40 :return: the value corresponding to the attribute.
41 :rtype: str,int,list,boolean
43 if name in self.__dict__:
44 return self.__dict__[name]
46 raise AttributeError(name + _(u" is not a valid option"))
48 def __setattr__(self, name, value):
49 '''Overwrite of the __setattr__ function to customize it for option usage
51 :param name str: The attribute to set.
52 :param value str: The value corresponding to the attribute.
56 object.__setattr__(self,name,value)
59 '''Class to manage all salomeTools options
64 # The options field stocks all options of a command in a list that contains dicts
66 # The list of available option type
67 self.availableOptions = ["boolean", "string", "int", "float", "long", "list", "list2"]
69 def add_option(self, shortName, longName, optionType, destName, helpString=""):
70 '''Method to add an option to a command. It gets all attributes of an option and append it in the options field
72 :param shortName str: The short name of the option (ex "l" for level option).
73 :param longName str: The long name of the option (ex "level" for level option).
74 :param optionType str: The type of the option (ex "int").
75 :param destName str: The name that will be used in the code.
76 :param helpString str: The text to display when user ask for help on a command.
81 option['shortName'] = shortName
82 option['longName'] = longName
84 if optionType not in self.availableOptions:
85 print("error optionType", optionType, "not available.")
88 option['optionType'] = optionType
89 option['destName'] = destName
90 option['helpString'] = helpString
91 option['result'] = None
92 self.options.append(option)
95 '''Method that display all options stored in self.options and there help
100 # Do nothing if there are no options
101 if len(self.options) == 0:
104 # for all options, print its values. "shortname" is an optional field of the options
105 print(printcolors.printcHeader(_("Available options are:")))
106 for option in self.options:
107 if 'shortName' in option and len(option['shortName']) > 0:
108 print(" -%(shortName)1s, --%(longName)s (%(optionType)s)\n\t%(helpString)s\n" % option)
110 print(" --%(longName)s (%(optionType)s)\n\t%(helpString)s\n" % option)
112 def parse_args(self, argList=None):
113 '''Method that instantiates the class OptResult that gives access to all options in the code
115 :param argList list: the raw list of arguments that were passed
116 :return: optResult, args : optResult is the option instance to manipulate in the code. args is the full raw list of passed options
117 :rtype: (class 'common.options.OptResult',list)
120 argList = sys.argv[1:]
122 # format shortNameOption and longNameOption to make right arguments to getopt.getopt function
125 for option in self.options:
126 shortNameOption = shortNameOption + option['shortName']
127 if option['shortName'] != "" and option['optionType'] != "boolean":
128 shortNameOption = shortNameOption + ":"
130 if option['longName'] != "":
131 if option['optionType'] != "boolean":
132 longNameOption.append(option['longName'] + "=")
134 longNameOption.append(option['longName'])
136 # call to getopt.getopt function to get the option passed in the command regarding the available options
137 optlist, args = getopt.getopt(argList, shortNameOption, longNameOption)
139 # instantiate and completing the optResult that will be returned
140 optResult = OptResult()
141 for option in self.options:
142 shortOption = "-" + option['shortName']
143 longOption = "--" + option['longName']
144 optionType = option['optionType']
146 if opt[0] in [shortOption, longOption]:
147 if optionType == "string":
148 option['result'] = opt[1]
149 elif optionType == "boolean":
150 option['result'] = True
151 elif optionType == "int":
152 option['result'] = int(opt[1])
153 elif optionType == "float":
154 option['result'] = float(opt[1])
155 elif optionType == "long":
156 option['result'] = long(opt[1])
157 elif optionType == "list":
158 if option['result'] is None:
159 option['result'] = list()
160 option['result'].append(opt[1])
161 elif optionType == "list2":
162 if option['result'] is None:
163 option['result'] = list()
164 if opt[1].find(",") == -1:
165 option['result'].append(opt[1])
167 elts = filter(lambda l: len(l) > 0, opt[1].split(","))
168 option['result'].extend(elts)
170 optResult.__setattr__(option['destName'], option['result'])
171 # free the option in order to be able to make a new free call of options (API case)
172 option['result'] = None
173 return optResult, args