Salome HOME
Merge branch 'agy/mem_peak_0_integ'
[modules/kernel.git] / src / Container / SALOME_PyNode.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2019  CEA/DEN, EDF R&D, OPEN CASCADE
3 #
4 # This library is free software; you can redistribute it and/or
5 # modify it under the terms of the GNU Lesser General Public
6 # License as published by the Free Software Foundation; either
7 # version 2.1 of the License, or (at your option) any later version.
8 #
9 # This library is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12 # Lesser General Public License for more details.
13 #
14 # You should have received a copy of the GNU Lesser General Public
15 # License along with this library; if not, write to the Free Software
16 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
17 #
18 # See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
19 #
20
21 #  File   : SALOME_PyNode.py
22 #  Author : Christian CAREMOLI, EDF
23 #  Module : SALOME
24 #  $Header$
25 #
26 import sys,traceback
27 import linecache
28 import pickle
29 import Engines__POA
30 import SALOME__POA
31 import SALOME
32
33 class Generic(SALOME__POA.GenericObj):
34   """A Python implementation of the GenericObj CORBA IDL"""
35   def __init__(self,poa):
36     self.poa=poa
37     self.cnt=1
38
39   def Register(self):
40     print("Register called : %d"%self.cnt)
41     self.cnt+=1
42
43   def UnRegister(self):
44     print("UnRegister called : %d"%self.cnt)
45     self.cnt-=1
46     if self.cnt <= 0:
47       oid=self.poa.servant_to_id(self)
48       self.poa.deactivate_object(oid)
49
50   def Destroy(self):
51     print("WARNING SALOME::GenericObj::Destroy() function is obsolete! Use UnRegister() instead.")
52     self.UnRegister()
53
54   def __del__(self):
55     print("Destuctor called")
56
57 class PyNode_i (Engines__POA.PyNode,Generic):
58   """The implementation of the PyNode CORBA IDL"""
59   def __init__(self, nodeName,code,poa,my_container):
60     """Initialize the node : compilation in the local context"""
61     Generic.__init__(self,poa)
62     self.nodeName=nodeName
63     self.code=code
64     self.my_container=my_container._container
65     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
66     ccode=compile(code,nodeName,'exec')
67     self.context={}
68     self.context["my_container"] = self.my_container
69     exec(ccode, self.context)
70
71   def getContainer(self):
72     return self.my_container
73
74   def getCode(self):
75     return self.code
76
77   def getName(self):
78     return self.nodeName
79
80   def defineNewCustomVar(self,varName,valueOfVar):
81     self.context[varName] = pickle.loads(valueOfVar)
82     pass
83
84   def executeAnotherPieceOfCode(self,code):
85     """Called for initialization of container lodging self."""
86     try:
87       ccode=compile(code,self.nodeName,'exec')
88       exec(ccode, self.context)
89     except:
90       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
91
92   def execute(self,funcName,argsin):
93     """Execute the function funcName found in local context with pickled args (argsin)"""
94     try:
95       argsin,kws=pickle.loads(argsin)
96       func=self.context[funcName]
97       argsout=func(*argsin,**kws)
98       argsout=pickle.dumps(argsout,-1)
99       return argsout
100     except:
101       exc_typ,exc_val,exc_fr=sys.exc_info()
102       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
103       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyNode: %s, function: %s" % (self.nodeName,funcName),0))
104
105 class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
106   """The implementation of the PyScriptNode CORBA IDL that executes a script"""
107   def __init__(self, nodeName,code,poa,my_container):
108     """Initialize the node : compilation in the local context"""
109     Generic.__init__(self,poa)
110     self.nodeName=nodeName
111     self.code=code
112     self.my_container=my_container._container
113     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
114     self.ccode=compile(code,nodeName,'exec')
115     self.context={}
116     self.context["my_container"] = self.my_container
117
118   def getContainer(self):
119     return self.my_container
120
121   def getCode(self):
122     return self.code
123
124   def getName(self):
125     return self.nodeName
126
127   def defineNewCustomVar(self,varName,valueOfVar):
128     self.context[varName] = pickle.loads(valueOfVar)
129     pass
130
131   def executeAnotherPieceOfCode(self,code):
132     """Called for initialization of container lodging self."""
133     try:
134       ccode=compile(code,self.nodeName,'exec')
135       exec(ccode, self.context)
136     except:
137       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
138
139   def assignNewCompiledCode(self,codeStr):
140     try:
141       self.code=codeStr
142       self.ccode=compile(codeStr,self.nodeName,'exec')
143     except:
144       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode.assignNewCompiledCode (%s) : code to be executed \"%s\"" %(self.nodeName,codeStr),0))
145
146   def execute(self,outargsname,argsin):
147     """Execute the script stored in attribute ccode with pickled args (argsin)"""
148     try:
149       argsname,kws=pickle.loads(argsin)
150       self.context.update(kws)
151       exec(self.ccode, self.context)
152       argsout=[]
153       for arg in outargsname:
154         if arg not in self.context:
155           raise KeyError("There is no variable %s in context" % arg)
156         argsout.append(self.context[arg])
157       argsout=pickle.dumps(tuple(argsout),-1)
158       return argsout
159     except:
160       exc_typ,exc_val,exc_fr=sys.exc_info()
161       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
162       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s, outargsname: %s" % (self.nodeName,outargsname),0))
163
164   def executeFirst(self,argsin):
165     """ Same than first part of self.execute to reduce memory peak."""
166     import time
167     try:
168       _,kws=pickle.loads(argsin)
169       self.context.update(kws)
170     except:
171       exc_typ,exc_val,exc_fr=sys.exc_info()
172       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
173       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:First %s" % (self.nodeName),0))
174
175   def executeSecond(self,outargsname):
176     """ Same than second part of self.execute to reduce memory peak."""
177     try:
178       exec(self.ccode, self.context)
179       argsout=[]
180       for arg in outargsname:
181         if arg not in self.context:
182           raise KeyError("There is no variable %s in context" % arg)
183         argsout.append(self.context[arg])
184       argsout=pickle.dumps(tuple(argsout),-1)
185       return argsout
186     except:
187       exc_typ,exc_val,exc_fr=sys.exc_info()
188       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
189       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:Second %s, outargsname: %s" % (self.nodeName,outargsname),0))
190
191   def getValueOfVarInContext(self,varName):
192     try:
193       return pickle.dumps(self.context[varName],-1)
194     except:
195       exc_typ,exc_val,exc_fr=sys.exc_info()
196       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
197       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
198     pass
199   
200   def assignVarInContext(self, varName, value):
201     try:
202       self.context[varName][0] = pickle.loads(value)
203     except:
204       exc_typ,exc_val,exc_fr=sys.exc_info()
205       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
206       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
207     pass
208
209   def callMethodOnVarInContext(self, varName, methodName, args):
210     try:
211       return pickle.dumps( getattr(self.context[varName][0],methodName)(*pickle.loads(args)),-1 )
212     except:
213       exc_typ,exc_val,exc_fr=sys.exc_info()
214       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
215       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
216     pass