2 //=============================================================================
3 // File : PyInterp_base.cxx
4 // Created : ven fév 7 10:01:36 CET 2003
5 // Author : Christian CAREMOLI, Paul RASCLE, EDF
7 // Copyright : EDF 2003
9 //=============================================================================
11 #include "PyInterp_base.h"
12 #include "utilities.h"
15 #include <cStringIO.h>
19 extern "C" PyObject * PyEval_EvalCode(PyObject *co, PyObject *g, PyObject *l);
21 static PyThreadState *savedThreadState = NULL;
24 * We have our own routines which are identical to the SIP routines
25 * to not depend from SIP software evolutions
28 extern "C" void salomeAcquireLock()
30 MESSAGE("salomeAcquireLock");
31 PyEval_RestoreThread(savedThreadState);
32 savedThreadState = NULL;
35 extern "C" void salomeReleaseLock()
37 MESSAGE("salomeReleaseLock");
38 savedThreadState = PyEval_SaveThread();
41 extern "C" int salomeCondAcquireLock()
43 MESSAGE("salomeCondAcquireLock");
44 if(savedThreadState != NULL)
47 * If savedThreadState is not NULL, Python global lock is not already acquired
49 * and return 1 to the caller
52 //MESSAGE("We got it (the lock)");
56 * If savedThreadState is NULL, Python global lock is already acquired
57 * We don't acquire or release it
58 * We return 0 to the caller
59 * CAUTION : it's only true when there is no event programming running (Tkinter, PyQt)
64 extern "C" void salomeCondReleaseLock(int rellock)
66 MESSAGE("salomeCondReleaseLock");
71 // main python interpreter
73 PyThreadState *PyInterp_base::_gtstate=0; // force 0 before execution
74 int PyInterp_base::_argc=1;
75 char* PyInterp_base::_argv[] = {""};
77 PyObject *PyInterp_base::builtinmodule=NULL;
78 PyObject *PyInterp_base::salome_shared_modules_module=NULL;
82 SCRUTE(PyInterp_base::_gtstate);
83 if (PyInterp_base::_gtstate) return;
84 Py_Initialize(); // Initialize the interpreter
85 PyEval_InitThreads(); // Create (and acquire) the interpreter lock
86 PySys_SetArgv(PyInterp_base::_argc,PyInterp_base::_argv); // initialize sys.argv
87 PyInterp_base::_gtstate = PyThreadState_Get();
88 SCRUTE(PyInterp_base::_gtstate);
91 // * Import __builtin__ module and store it to use it with all sub-interpreters
92 // * This hack could be used with event programming (PyQt) to avoid errors
93 // * encountered with incoherent builtins
96 // PyInterp_base::builtinmodule =PyImport_ImportModule("__builtin__");
97 // SCRUTE(PyInterp_base::builtinmodule->ob_refcnt);
100 * Import salome_shared_modules module and store it to use it with all sub-interpreters
103 PyInterp_base::salome_shared_modules_module =PyImport_ImportModule("salome_shared_modules");
104 if(PyInterp_base::salome_shared_modules_module == NULL){
105 MESSAGE("init_python: problem with salome_shared_modules import");
111 SCRUTE(PyInterp_base::salome_shared_modules_module->ob_refcnt);
116 * This function compiles a string (command) and then evaluates it in the dictionnary
117 * context if possible.
120 * 1 : incomplete text
121 * 0 : complete text executed with success
124 int compile_command(const char *command,PyObject *context)
129 m=PyImport_AddModule("codeop");
133 * Fatal error. No way to go on.
138 v= PyObject_CallMethod(m,"compile_command","s",command);
142 * Error encountered. It should be SyntaxError
143 * so we don't write out traceback
145 PyObject *exception,*value,*tb;
146 PyErr_Fetch(&exception, &value, &tb);
147 PyErr_NormalizeException(&exception, &value, &tb);
148 PyErr_Display(exception, value, NULL);
149 Py_XDECREF(exception);
155 else if (v == Py_None)
158 * Incomplete text we return 1 : we need a complete text to execute
165 * Complete and correct text. We evaluate it.
167 r = PyEval_EvalCode(v,context,context);
172 * Execution error. We return -1
179 * The command has been successfully executed. Return 0
186 * basic constructor here : herited classes constructors must call initalize() method
190 PyInterp_base::PyInterp_base():_tstate(0),_vout(0),_verr(0),_g(0),_atFirst(true)
192 MESSAGE("PyInterp_base::PyInterp_base()");
195 PyInterp_base::~PyInterp_base()
197 MESSAGE("PyInterp_base::~PyInterp_base()");
199 PyThreadState_Swap(_tstate);
200 Py_EndInterpreter(_tstate);
205 * Must be called by herited classes constructors. initialize() calls virtuals methods
206 * initstate & initcontext, not defined here in base class. initstate & initcontext methods
207 * must be implemented in herited classes, following the Python interpreter policy
208 * (mono or multi interpreter...).
210 void PyInterp_base::initialize()
212 MESSAGE("PyInterp_base::initialize()");
215 _history.clear(); // start a new list of user's commands
216 _ith = _history.begin();
224 m=PyImport_ImportModule("codeop"); // used to interpret & compile commands
227 MESSAGE("Problem...");
236 * Create cStringIO to capture stdout and stderr
239 PycStringIO=(PycStringIO_CAPI *)xxxPyCObject_Import("cStringIO", "cStringIO_CAPI");
240 _vout=PycStringIO->NewOutput(128);
241 _verr=PycStringIO->NewOutput(128);
243 // All the initRun outputs are redirected to the standard output (console)
246 // We go out of Python world to enter the C++ world. Release the Python global lock
252 string PyInterp_base::getbanner()
254 MESSAGE("PyInterp_base::getbanner()");
255 string banner = "Python ";
256 banner = banner + Py_GetVersion() + " on " + Py_GetPlatform() ;
257 banner = banner + "\ntype help to get general information on environment\n";
258 return banner.c_str();
261 int PyInterp_base::initRun()
263 MESSAGE("PyInterp_base::initRun()");
264 PySys_SetObject("stderr",_verr);
265 PySys_SetObject("stdout",_vout);
267 PyObject *v = PyObject_CallMethod(_verr,"reset","");
269 v = PyObject_CallMethod(_vout,"reset","");
274 m = PyImport_GetModuleDict();
276 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
277 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
279 MESSAGE(this->getvout());
280 MESSAGE(this->getverr());
285 void PyInterp_base::enter()
287 MESSAGE("PyInterp_base::enter()");
289 PyThreadState_Swap(_tstate);
292 void PyInterp_base::quit()
294 MESSAGE("PyInterp_base::quit()");
298 void PyInterp_base::basicRun(const char *command)
303 code=Py_CompileString((char *)command,"PyInterp_base",Py_file_input);
307 * Caught an error : SyntaxError
314 r = PyEval_EvalCode(code,_g,_g);
319 * Caught an error during execution
330 int PyInterp_base::run(const char *command)
337 ret = this->simpleRun("from Help import *");
338 MESSAGE(this->getvout())
339 MESSAGE(this->getverr())
340 if (ret != 0) return ret;
341 ret = this->simpleRun("import salome");
342 MESSAGE(this->getvout());
343 MESSAGE(this->getverr())
344 if (ret != 0) return ret;
346 ret = this->simpleRun(command);
350 int PyInterp_base::simpleRun(const char *command)
353 PyObject *v,*m,*r,*g;
356 string s_com = command;
358 if (s_com.size() > 0)
360 _history.push_back(s_com);
361 _ith = _history.end();
362 SCRUTE(_history.back());
367 // We come from C++ to enter Python world
368 // We need to acquire the Python global lock
370 // Restore the sub interpreter thread state : this._tstate
371 PyThreadState_Swap(_tstate);
374 Reset redirected outputs before treatment
376 PySys_SetObject("stderr",_verr);
377 PySys_SetObject("stdout",_vout);
379 v = PyObject_CallMethod(_verr,"reset","");
381 v = PyObject_CallMethod(_vout,"reset","");
384 ier=compile_command(command,_g);
386 // Outputs are redirected on standards outputs (console)
387 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
388 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
390 // We go back to the C++ world. Release the lock.
395 static string vout_buffer;
396 static string verr_buffer;
398 char * PyInterp_base::getverr()
400 MESSAGE("PyInterp_base::getverr");
402 v=PycStringIO->cgetvalue(_verr);
403 verr_buffer=PyString_AsString(v);
405 return (char *)verr_buffer.c_str();
408 char * PyInterp_base::getvout()
410 MESSAGE("PyInterp_base::getvout");
412 v=PycStringIO->cgetvalue(_vout);
413 vout_buffer=PyString_AsString(v);
415 return (char *)vout_buffer.c_str();
418 const char * PyInterp_base::getPrevious()
420 MESSAGE("PyInterp_base::getPrevious");
421 if (_ith != _history.begin())
424 return (*_ith).c_str();
427 return BEGIN_HISTORY_PY;
430 const char * PyInterp_base::getNext()
432 MESSAGE("PyInterp_base::getNext");
433 if (_ith != _history.end())
437 if (_ith == _history.end())
438 return TOP_HISTORY_PY;
440 return (*_ith).c_str();