2
2
3
3
""" Module for executing actions """
4
4
5
- #- ------------------------------------------------------------------------------
5
+ # ------------------------------------------------------------------------------
6
6
# Name: Actions
7
7
# Purpose:
8
8
#
11
11
# Created: 09/10/2013
12
12
# Copyright: (c) michel.vincent 2013
13
13
# Licence: GPL
14
- #- ------------------------------------------------------------------------------
14
+ # ------------------------------------------------------------------------------
15
15
16
16
17
17
# Imports
18
- from pkgutil import walk_packages , extend_path
18
+ from pkgutil import walk_packages
19
19
from collections import OrderedDict as ODict
20
20
from importlib import import_module
21
21
from time import sleep
22
22
import __builtin__
23
- import logging
24
- import os , sys
25
23
26
24
27
25
# Imports from constants
28
26
from sequence .common .constant import LOGGER
29
- from sequence import action as action_package
27
+ from sequence import action as action_package
30
28
from sequence .action import user as user_action_package
31
29
32
30
@@ -52,7 +50,7 @@ def get_action_list():
52
50
for _ , module_name , _ in walk_packages (path , prefix ):
53
51
try :
54
52
module = import_module (module_name )
55
- except Exception as exc :
53
+ except Exception :
56
54
pass
57
55
else :
58
56
action_class = get_action_from_module (module )
@@ -97,7 +95,8 @@ def process_module(module_name, with_parameters=True):
97
95
try :
98
96
default_parameters = parse_default_parameters (parameters_string )
99
97
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 ))
101
100
msg = msg .format (module_name )
102
101
raise ActionCreationError (msg )
103
102
else :
@@ -138,12 +137,12 @@ def cast_parameters(xml_block, default_parameters):
138
137
try :
139
138
if isinstance (default_parameters [name ], bool ) and \
140
139
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 ()
147
146
else :
148
147
cast_value = type (default_parameters [name ])(value )
149
148
except :
@@ -160,30 +159,40 @@ def cast_parameters(xml_block, default_parameters):
160
159
return result
161
160
162
161
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
+
163
183
def parse_default_parameters (parameters ):
164
184
"""
165
185
Return a dictionnary from the default parameters string
166
186
"""
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 )
180
188
181
189
182
190
# BaseEnum class definiton
183
191
class BaseEnum (unicode ):
184
192
""" Base class for enumerations in action parameters """
185
193
pass
186
194
195
+
187
196
# Create enumerations in action parameters
188
197
def enum_type (* args ):
189
198
"""
@@ -193,30 +202,37 @@ def enum_type(*args):
193
202
for arg in args :
194
203
if not isinstance (arg , basestring ):
195
204
msg = "{} is not a string" .format (arg )
196
- raise AttributeError
205
+ raise TypeError (msg )
206
+
197
207
# Format strings
198
208
values = [arg .strip () for arg in args ]
209
+
199
210
# Create MetaEnum
200
211
values_property = property (lambda cls : values )
201
- MetaEnum = type ("MetaEnum" , (type ,), {"values" :values_property })
212
+ MetaEnum = type ("MetaEnum" , (type ,), {"values" : values_property })
213
+
202
214
# __new__ method
203
215
def __new__ (cls , value ):
204
216
if value not in cls .values :
205
217
msg = "'{}' not in {}" .format (value , cls .values )
206
218
raise AttributeError (msg )
207
219
return BaseEnum .__new__ (cls , value )
220
+
208
221
# __repr__ method
209
222
def __repr__ (self ):
210
223
return u"Element '{}' of Enum({})" .format (unicode (self ), self .values )
224
+
211
225
# method dictionnary
212
226
method_dict = {"__new__" : __new__ ,
213
227
"__repr__" : __repr__ ,
214
228
"values" : property (lambda self : self .__class__ .values )}
229
+
215
230
# Create EnumType
216
231
return MetaEnum ("EnumType" , (BaseEnum ,), method_dict )
217
232
233
+
218
234
# Abstract action class definition
219
- class AbstractAction (object ) :
235
+ class AbstractAction (object ):
220
236
"""
221
237
Class providing a basis for action creation and execution
222
238
"""
@@ -239,7 +255,7 @@ def set_default_parameters(cls, params):
239
255
raise ActionCreationError (msg )
240
256
setattr (cls , name , value )
241
257
242
- def __init__ (self , name , module , iteration , tick , parameters ) :
258
+ def __init__ (self , name , module , iteration , tick , parameters ):
243
259
"""
244
260
Initialize action
245
261
"""
@@ -257,7 +273,7 @@ def __init__(self, name, module, iteration, tick, parameters) :
257
273
for name , value in parameters .items ():
258
274
setattr (self , name , value )
259
275
260
- def execute (self , stop_thread , log_dict ) :
276
+ def execute (self , stop_thread , log_dict ):
261
277
"""
262
278
Execute action and log it with the stop mecanism and logging dictionary
263
279
"""
@@ -268,10 +284,10 @@ def execute(self, stop_thread, log_dict) :
268
284
self .warning ('The stop mecanism has been activated before Pre_run' )
269
285
return False
270
286
# Try PreRun
271
- try :
287
+ try :
272
288
self .info ('PreRun' )
273
289
self ._valid_pre_run_flag = self .pre_run ()
274
- except Exception as exc :
290
+ except Exception as exc :
275
291
self .error ('PreRun failed:' )
276
292
self .error (repr (exc ))
277
293
# Warning if PreRun returned False
@@ -283,14 +299,14 @@ def execute(self, stop_thread, log_dict) :
283
299
# If PreRun returned True
284
300
elif self ._valid_pre_run_flag :
285
301
# Log info
286
- if self ._iteration == 1 :
302
+ if self ._iteration == 1 :
287
303
self .info ('Run' )
288
- else :
304
+ else :
289
305
self .info ('Run ({} iterations)' .format (self ._iteration ))
290
306
# Run Loop
291
- for i in range (self ._iteration ) :
307
+ for i in range (self ._iteration ):
292
308
# Try Run
293
- try :
309
+ try :
294
310
run_result = self .run ()
295
311
except Exception as exc :
296
312
self .error ('Run failed on execution {}:' .format (i + 1 ))
@@ -317,7 +333,7 @@ def execute(self, stop_thread, log_dict) :
317
333
self .warning (msg )
318
334
break
319
335
# Try Post run
320
- try :
336
+ try :
321
337
self .info ('PostRun' )
322
338
result = self .post_run ()
323
339
except Exception as exc :
@@ -377,11 +393,10 @@ def critical(self, msg):
377
393
# Action Creation Error class definition
378
394
class ActionCreationError (StandardError ):
379
395
""" Custom error raised when an action creation error is detected """
380
- def __init__ (self , strerror ) :
396
+
397
+ def __init__ (self , strerror ):
381
398
StandardError .__init__ (self , strerror )
382
399
self .strerror = strerror
383
400
384
- def __str__ (self ) :
401
+ def __str__ (self ):
385
402
return self .strerror
386
-
387
-
0 commit comments