Salome HOME
venv directory is configured in config_appli.xml file
[modules/kernel.git] / src / Container / SALOME_PyNode.py
1 #  -*- coding: iso-8859-1 -*-
2 # Copyright (C) 2007-2021  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     pass
57
58 class PyNode_i (Engines__POA.PyNode,Generic):
59   """The implementation of the PyNode CORBA IDL"""
60   def __init__(self, nodeName,code,poa,my_container):
61     """Initialize the node : compilation in the local context"""
62     Generic.__init__(self,poa)
63     self.nodeName=nodeName
64     self.code=code
65     self.my_container=my_container._container
66     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
67     ccode=compile(code,nodeName,'exec')
68     self.context={}
69     self.context["my_container"] = self.my_container
70     exec(ccode, self.context)
71
72   def getContainer(self):
73     return self.my_container
74
75   def getCode(self):
76     return self.code
77
78   def getName(self):
79     return self.nodeName
80
81   def defineNewCustomVar(self,varName,valueOfVar):
82     self.context[varName] = pickle.loads(valueOfVar)
83     pass
84
85   def executeAnotherPieceOfCode(self,code):
86     """Called for initialization of container lodging self."""
87     try:
88       ccode=compile(code,self.nodeName,'exec')
89       exec(ccode, self.context)
90     except Exception:
91       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
92
93   def execute(self,funcName,argsin):
94     """Execute the function funcName found in local context with pickled args (argsin)"""
95     try:
96       argsin,kws=pickle.loads(argsin)
97       func=self.context[funcName]
98       argsout=func(*argsin,**kws)
99       argsout=pickle.dumps(argsout,-1)
100       return argsout
101     except Exception:
102       exc_typ,exc_val,exc_fr=sys.exc_info()
103       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
104       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyNode: %s, function: %s" % (self.nodeName,funcName),0))
105
106 class PyScriptNode_i (Engines__POA.PyScriptNode,Generic):
107   """The implementation of the PyScriptNode CORBA IDL that executes a script"""
108   def __init__(self, nodeName,code,poa,my_container):
109     """Initialize the node : compilation in the local context"""
110     Generic.__init__(self,poa)
111     self.nodeName=nodeName
112     self.code=code
113     self.my_container=my_container._container
114     linecache.cache[nodeName]=0,None,code.split('\n'),nodeName
115     self.ccode=compile(code,nodeName,'exec')
116     self.context={}
117     self.context["my_container"] = self.my_container
118
119   def getContainer(self):
120     return self.my_container
121
122   def getCode(self):
123     return self.code
124
125   def getName(self):
126     return self.nodeName
127
128   def defineNewCustomVar(self,varName,valueOfVar):
129     self.context[varName] = pickle.loads(valueOfVar)
130     pass
131
132   def executeAnotherPieceOfCode(self,code):
133     """Called for initialization of container lodging self."""
134     try:
135       ccode=compile(code,self.nodeName,'exec')
136       exec(ccode, self.context)
137     except Exception:
138       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode (%s) : code to be executed \"%s\"" %(self.nodeName,code),0))
139
140   def assignNewCompiledCode(self,codeStr):
141     try:
142       self.code=codeStr
143       self.ccode=compile(codeStr,self.nodeName,'exec')
144     except Exception:
145       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"","PyScriptNode.assignNewCompiledCode (%s) : code to be executed \"%s\"" %(self.nodeName,codeStr),0))
146
147   def execute(self,outargsname,argsin):
148     """Execute the script stored in attribute ccode with pickled args (argsin)"""
149     try:
150       argsname,kws=pickle.loads(argsin)
151       self.context.update(kws)
152       exec(self.ccode, self.context)
153       argsout=[]
154       for arg in outargsname:
155         if arg not in self.context:
156           raise KeyError("There is no variable %s in context" % arg)
157         argsout.append(self.context[arg])
158       argsout=pickle.dumps(tuple(argsout),-1)
159       return argsout
160     except Exception:
161       exc_typ,exc_val,exc_fr=sys.exc_info()
162       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
163       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s, outargsname: %s" % (self.nodeName,outargsname),0))
164
165   def executeFirst(self,argsin):
166     """ Same than first part of self.execute to reduce memory peak."""
167     import time
168     try:
169       _,kws=pickle.loads(argsin)
170       self.context.update(kws)
171     except Exception:
172       exc_typ,exc_val,exc_fr=sys.exc_info()
173       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
174       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:First %s" % (self.nodeName),0))
175
176   def executeSecond(self,outargsname):
177     """ Same than second part of self.execute to reduce memory peak."""
178     try:
179       exec(self.ccode, self.context)
180       argsout=[]
181       for arg in outargsname:
182         if arg not in self.context:
183           raise KeyError("There is no variable %s in context" % arg)
184         argsout.append(self.context[arg])
185       argsout=pickle.dumps(tuple(argsout),-1)
186       return argsout
187     except Exception:
188       exc_typ,exc_val,exc_fr=sys.exc_info()
189       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
190       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode:Second %s, outargsname: %s" % (self.nodeName,outargsname),0))
191
192   def getValueOfVarInContext(self,varName):
193     try:
194       return pickle.dumps(self.context[varName],-1)
195     except Exception:
196       exc_typ,exc_val,exc_fr=sys.exc_info()
197       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
198       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
199     pass
200   
201   def assignVarInContext(self, varName, value):
202     try:
203       self.context[varName][0] = pickle.loads(value)
204     except Exception:
205       exc_typ,exc_val,exc_fr=sys.exc_info()
206       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
207       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
208     pass
209
210   def callMethodOnVarInContext(self, varName, methodName, args):
211     try:
212       return pickle.dumps( getattr(self.context[varName][0],methodName)(*pickle.loads(args)),-1 )
213     except Exception:
214       exc_typ,exc_val,exc_fr=sys.exc_info()
215       l=traceback.format_exception(exc_typ,exc_val,exc_fr)
216       raise SALOME.SALOME_Exception(SALOME.ExceptionStruct(SALOME.BAD_PARAM,"".join(l),"PyScriptNode: %s" %self.nodeName,0))
217     pass