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 command
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
38 :param name str: The attribute to get the value.
39 :return: the value corresponding to the attribute.
40 :rtype: str,int,list,boolean
42 if name in self.__dict__:
43 return self.__dict__[name]
45 raise AttributeError(name + _(u" is not a valid option"))
47 def __setattr__(self, name, value):
48 '''Overwrite of the __setattr__ function to customize it for option usage
49 :param name str: The attribute to set.
50 :param value str: The value corresponding to the attribute.
54 object.__setattr__(self,name,value)
57 '''Class to manage all salomeTools options
62 # The options field stocks all options of a command in a list that contains dicts
64 # The list of available option type
65 self.availableOptions = ["boolean", "string", "int", "float", "long", "list", "list2"]
67 def add_option(self, shortName, longName, optionType, destName, helpString=""):
68 '''Method to add an option to a command. It gets all attributes of an option and append it in the options field
69 :param shortName str: The short name of the option (ex "l" for level option).
70 :param longName str: The long name of the option (ex "level" for level option).
71 :param optionType str: The type of the option (ex "int").
72 :param destName str: The name that will be used in the code.
73 :param helpString str: The text to display when user ask for help on a command.
78 option['shortName'] = shortName
79 option['longName'] = longName
81 if optionType not in self.availableOptions:
82 print("error optionType", optionType, "not available.")
85 option['optionType'] = optionType
86 option['destName'] = destName
87 option['helpString'] = helpString
88 option['result'] = None
89 self.options.append(option)
92 '''Method that display all options stored in self.options and there help
96 # Do nothing if there are no options
97 if len(self.options) == 0:
100 # for all options, print its values. "shortname" is an optional field of the options
101 print(printcolors.printcHeader(_("Available options are:")))
102 for option in self.options:
103 if 'shortName' in option and len(option['shortName']) > 0:
104 print(" -%(shortName)1s, --%(longName)s (%(optionType)s)\n\t%(helpString)s\n" % option)
106 print(" --%(longName)s (%(optionType)s)\n\t%(helpString)s\n" % option)
108 def parse_args(self, argList=None):
109 '''Method that instantiates the class OptResult that gives access to all options in the code
110 :param argList list: the raw list of arguments that were passed
111 :return: optResult, args : optResult is the option instance to manipulate in the code. args is the full raw list of passed options
112 :rtype: (class 'common.options.OptResult',list)
115 argList = sys.argv[1:]
117 # format shortNameOption and longNameOption to make right arguments to getopt.getopt function
120 for option in self.options:
121 shortNameOption = shortNameOption + option['shortName']
122 if option['shortName'] != "" and option['optionType'] != "boolean":
123 shortNameOption = shortNameOption + ":"
125 if option['longName'] != "":
126 if option['optionType'] != "boolean":
127 longNameOption.append(option['longName'] + "=")
129 longNameOption.append(option['longName'])
131 # call to getopt.getopt function to get the option passed in the command regarding the available options
132 optlist, args = getopt.getopt(argList, shortNameOption, longNameOption)
134 # instantiate and completing the optResult that will be returned
135 optResult = OptResult()
136 for option in self.options:
137 shortOption = "-" + option['shortName']
138 longOption = "--" + option['longName']
139 optionType = option['optionType']
141 if opt[0] in [shortOption, longOption]:
142 if optionType == "string":
143 option['result'] = opt[1]
144 elif optionType == "boolean":
145 option['result'] = True
146 elif optionType == "int":
147 option['result'] = int(opt[1])
148 elif optionType == "float":
149 option['result'] = float(opt[1])
150 elif optionType == "long":
151 option['result'] = long(opt[1])
152 elif optionType == "list":
153 if option['result'] is None:
154 option['result'] = list()
155 option['result'].append(opt[1])
156 elif optionType == "list2":
157 if option['result'] is None:
158 option['result'] = list()
159 if opt[1].find(",") == -1:
160 option['result'].append(opt[1])
162 elts = filter(lambda l: len(l) > 0, opt[1].split(","))
163 option['result'].extend(elts)
165 optResult.__setattr__(option['destName'], option['result'])
166 return optResult, args