22
33""" Module for executing actions """
44
5- #- ------------------------------------------------------------------------------
5+ # ------------------------------------------------------------------------------
66# Name: Actions
77# Purpose:
88#
1111# Created: 09/10/2013
1212# Copyright: (c) michel.vincent 2013
1313# Licence: GPL
14- #- ------------------------------------------------------------------------------
14+ # ------------------------------------------------------------------------------
1515
1616
1717# Imports
18- from pkgutil import walk_packages , extend_path
18+ from pkgutil import walk_packages
1919from collections import OrderedDict as ODict
2020from importlib import import_module
2121from time import sleep
2222import __builtin__
23- import logging
24- import os , sys
2523
2624
2725# Imports from constants
2826from sequence .common .constant import LOGGER
29- from sequence import action as action_package
27+ from sequence import action as action_package
3028from sequence .action import user as user_action_package
3129
3230
@@ -52,7 +50,7 @@ def get_action_list():
5250 for _ , module_name , _ in walk_packages (path , prefix ):
5351 try :
5452 module = import_module (module_name )
55- except Exception as exc :
53+ except Exception :
5654 pass
5755 else :
5856 action_class = get_action_from_module (module )
@@ -97,7 +95,8 @@ def process_module(module_name, with_parameters=True):
9795 try :
9896 default_parameters = parse_default_parameters (parameters_string )
9997 except Exception as e :
100- msg = str ("Error while parsing parameters of action module '{}'" .format (e ))
98+ msg = str ("Error while parsing parameters of action module '{}'"
99+ .format (e ))
101100 msg = msg .format (module_name )
102101 raise ActionCreationError (msg )
103102 else :
@@ -138,12 +137,12 @@ def cast_parameters(xml_block, default_parameters):
138137 try :
139138 if isinstance (default_parameters [name ], bool ) and \
140139 isinstance (value , basestring ):
141- if value .lower () in ["true" , "1" ]:
142- cast_value = True
143- elif value .lower () in ["false" , "0" ]:
144- cast_value = False
145- else :
146- raise Exception ()
140+ if value .lower () in ["true" , "1" ]:
141+ cast_value = True
142+ elif value .lower () in ["false" , "0" ]:
143+ cast_value = False
144+ else :
145+ raise Exception ()
147146 else :
148147 cast_value = type (default_parameters [name ])(value )
149148 except :
@@ -160,30 +159,40 @@ def cast_parameters(xml_block, default_parameters):
160159 return result
161160
162161
162+ def parse_value (value , vtype ):
163+ """
164+ Return a value for two strings (value and type)
165+ """
166+ if ',' in vtype :
167+ return enum_type (* vtype .split ("," ))(value )
168+ if vtype .lower () == 'bool' :
169+ if value .lower () not in ['true' , '1' , 'false' , '0' ]:
170+ raise TypeError ('{} is not a valid bool' .format (value ))
171+ return value .lower () in ['true' , '1' ]
172+ return getattr (__builtin__ , vtype .lower ())(value )
173+
174+
175+ def parse_line (line ):
176+ """
177+ Return a (name, value) tuple from a parameter line.
178+ """
179+ name , value , vtype = (e .strip () for e in line .split (':' ))
180+ return name , parse_value (value , vtype )
181+
182+
163183def parse_default_parameters (parameters ):
164184 """
165185 Return a dictionnary from the default parameters string
166186 """
167- # Amazingly monstruous magical one-liner
168- return ODict ((name ,getattr (__builtin__ , vtype .lower ())(value ))
169- if (vtype .lower () != "bool" and "," not in vtype )
170- else (name ,True ) if (value .lower () in ["true" ,"1" ]
171- and vtype .lower () == "bool" )
172- else (name ,False ) if (value .lower () in ["false" ,"0" ]
173- and vtype .lower () == "bool" )
174- else 0 if vtype .lower () == "bool"
175- else (name , enum_type (* vtype .split ("," ))(value ))
176- for name , value , vtype in (tuple (e .strip ()
177- for e in line .split (":" ))
178- for line in parameters .split ("\n " )
179- if line ))
187+ return ODict (parse_line (line ) for line in parameters .split ("\n " ) if line )
180188
181189
182190# BaseEnum class definiton
183191class BaseEnum (unicode ):
184192 """ Base class for enumerations in action parameters """
185193 pass
186194
195+
187196# Create enumerations in action parameters
188197def enum_type (* args ):
189198 """
@@ -193,30 +202,37 @@ def enum_type(*args):
193202 for arg in args :
194203 if not isinstance (arg , basestring ):
195204 msg = "{} is not a string" .format (arg )
196- raise AttributeError
205+ raise TypeError (msg )
206+
197207 # Format strings
198208 values = [arg .strip () for arg in args ]
209+
199210 # Create MetaEnum
200211 values_property = property (lambda cls : values )
201- MetaEnum = type ("MetaEnum" , (type ,), {"values" :values_property })
212+ MetaEnum = type ("MetaEnum" , (type ,), {"values" : values_property })
213+
202214 # __new__ method
203215 def __new__ (cls , value ):
204216 if value not in cls .values :
205217 msg = "'{}' not in {}" .format (value , cls .values )
206218 raise AttributeError (msg )
207219 return BaseEnum .__new__ (cls , value )
220+
208221 # __repr__ method
209222 def __repr__ (self ):
210223 return u"Element '{}' of Enum({})" .format (unicode (self ), self .values )
224+
211225 # method dictionnary
212226 method_dict = {"__new__" : __new__ ,
213227 "__repr__" : __repr__ ,
214228 "values" : property (lambda self : self .__class__ .values )}
229+
215230 # Create EnumType
216231 return MetaEnum ("EnumType" , (BaseEnum ,), method_dict )
217232
233+
218234# Abstract action class definition
219- class AbstractAction (object ) :
235+ class AbstractAction (object ):
220236 """
221237 Class providing a basis for action creation and execution
222238 """
@@ -239,7 +255,7 @@ def set_default_parameters(cls, params):
239255 raise ActionCreationError (msg )
240256 setattr (cls , name , value )
241257
242- def __init__ (self , name , module , iteration , tick , parameters ) :
258+ def __init__ (self , name , module , iteration , tick , parameters ):
243259 """
244260 Initialize action
245261 """
@@ -257,7 +273,7 @@ def __init__(self, name, module, iteration, tick, parameters) :
257273 for name , value in parameters .items ():
258274 setattr (self , name , value )
259275
260- def execute (self , stop_thread , log_dict ) :
276+ def execute (self , stop_thread , log_dict ):
261277 """
262278 Execute action and log it with the stop mecanism and logging dictionary
263279 """
@@ -268,10 +284,10 @@ def execute(self, stop_thread, log_dict) :
268284 self .warning ('The stop mecanism has been activated before Pre_run' )
269285 return False
270286 # Try PreRun
271- try :
287+ try :
272288 self .info ('PreRun' )
273289 self ._valid_pre_run_flag = self .pre_run ()
274- except Exception as exc :
290+ except Exception as exc :
275291 self .error ('PreRun failed:' )
276292 self .error (repr (exc ))
277293 # Warning if PreRun returned False
@@ -283,14 +299,14 @@ def execute(self, stop_thread, log_dict) :
283299 # If PreRun returned True
284300 elif self ._valid_pre_run_flag :
285301 # Log info
286- if self ._iteration == 1 :
302+ if self ._iteration == 1 :
287303 self .info ('Run' )
288- else :
304+ else :
289305 self .info ('Run ({} iterations)' .format (self ._iteration ))
290306 # Run Loop
291- for i in range (self ._iteration ) :
307+ for i in range (self ._iteration ):
292308 # Try Run
293- try :
309+ try :
294310 run_result = self .run ()
295311 except Exception as exc :
296312 self .error ('Run failed on execution {}:' .format (i + 1 ))
@@ -317,7 +333,7 @@ def execute(self, stop_thread, log_dict) :
317333 self .warning (msg )
318334 break
319335 # Try Post run
320- try :
336+ try :
321337 self .info ('PostRun' )
322338 result = self .post_run ()
323339 except Exception as exc :
@@ -377,11 +393,10 @@ def critical(self, msg):
377393# Action Creation Error class definition
378394class ActionCreationError (StandardError ):
379395 """ Custom error raised when an action creation error is detected """
380- def __init__ (self , strerror ) :
396+
397+ def __init__ (self , strerror ):
381398 StandardError .__init__ (self , strerror )
382399 self .strerror = strerror
383400
384- def __str__ (self ) :
401+ def __str__ (self ):
385402 return self .strerror
386-
387-
0 commit comments