1 // SALOME SALOMEGUI : implementation of desktop and GUI kernel
3 // Copyright (C) 2003 CEA/DEN, EDF R&D
7 // File : PyInterp_base.cxx
8 // Author : Christian CAREMOLI, Paul RASCLE, EDF
13 #include "PyInterp_base.h"
14 #include "utilities.h"
17 #include <cStringIO.h>
21 extern "C" PyObject * PyEval_EvalCode(PyObject *co, PyObject *g, PyObject *l);
23 static PyThreadState *savedThreadState = NULL;
26 * We have our own routines which are identical to the SIP routines
27 * to not depend from SIP software evolutions
30 extern "C" void salomeAcquireLock()
32 MESSAGE("salomeAcquireLock");
33 PyEval_RestoreThread(savedThreadState);
34 savedThreadState = NULL;
37 extern "C" void salomeReleaseLock()
39 MESSAGE("salomeReleaseLock");
40 savedThreadState = PyEval_SaveThread();
43 extern "C" int salomeCondAcquireLock()
45 MESSAGE("salomeCondAcquireLock");
46 if(savedThreadState != NULL)
49 * If savedThreadState is not NULL, Python global lock is not already acquired
51 * and return 1 to the caller
54 //MESSAGE("We got it (the lock)");
58 * If savedThreadState is NULL, Python global lock is already acquired
59 * We don't acquire or release it
60 * We return 0 to the caller
61 * CAUTION : it's only true when there is no event programming running (Tkinter, PyQt)
66 extern "C" void salomeCondReleaseLock(int rellock)
68 MESSAGE("salomeCondReleaseLock");
73 // main python interpreter
75 PyThreadState *PyInterp_base::_gtstate=0; // force 0 before execution
76 int PyInterp_base::_argc=1;
77 char* PyInterp_base::_argv[] = {""};
79 PyObject *PyInterp_base::builtinmodule=NULL;
80 PyObject *PyInterp_base::salome_shared_modules_module=NULL;
84 SCRUTE(PyInterp_base::_gtstate);
85 if (PyInterp_base::_gtstate) return;
86 Py_Initialize(); // Initialize the interpreter
87 PyEval_InitThreads(); // Create (and acquire) the interpreter lock
88 PySys_SetArgv(PyInterp_base::_argc,PyInterp_base::_argv); // initialize sys.argv
89 PyInterp_base::_gtstate = PyThreadState_Get();
90 SCRUTE(PyInterp_base::_gtstate);
93 // * Import __builtin__ module and store it to use it with all sub-interpreters
94 // * This hack could be used with event programming (PyQt) to avoid errors
95 // * encountered with incoherent builtins
98 // PyInterp_base::builtinmodule =PyImport_ImportModule("__builtin__");
99 // SCRUTE(PyInterp_base::builtinmodule->ob_refcnt);
102 * Import salome_shared_modules module and store it to use it with all sub-interpreters
105 PyInterp_base::salome_shared_modules_module =PyImport_ImportModule("salome_shared_modules");
106 if(PyInterp_base::salome_shared_modules_module == NULL){
107 MESSAGE("init_python: problem with salome_shared_modules import");
113 SCRUTE(PyInterp_base::salome_shared_modules_module->ob_refcnt);
118 * This function compiles a string (command) and then evaluates it in the dictionnary
119 * context if possible.
122 * 1 : incomplete text
123 * 0 : complete text executed with success
126 int compile_command(const char *command,PyObject *context)
131 m=PyImport_AddModule("codeop");
135 * Fatal error. No way to go on.
140 v= PyObject_CallMethod(m,"compile_command","s",command);
144 * Error encountered. It should be SyntaxError
145 * so we don't write out traceback
147 PyObject *exception,*value,*tb;
148 PyErr_Fetch(&exception, &value, &tb);
149 PyErr_NormalizeException(&exception, &value, &tb);
150 PyErr_Display(exception, value, NULL);
151 Py_XDECREF(exception);
157 else if (v == Py_None)
160 * Incomplete text we return 1 : we need a complete text to execute
167 * Complete and correct text. We evaluate it.
169 r = PyEval_EvalCode(v,context,context);
174 * Execution error. We return -1
181 * The command has been successfully executed. Return 0
188 * basic constructor here : herited classes constructors must call initalize() method
192 PyInterp_base::PyInterp_base():_tstate(0),_vout(0),_verr(0),_g(0),_atFirst(true)
194 MESSAGE("PyInterp_base::PyInterp_base()");
197 PyInterp_base::~PyInterp_base()
199 MESSAGE("PyInterp_base::~PyInterp_base()");
201 PyThreadState_Swap(_tstate);
202 Py_EndInterpreter(_tstate);
207 * Must be called by herited classes constructors. initialize() calls virtuals methods
208 * initstate & initcontext, not defined here in base class. initstate & initcontext methods
209 * must be implemented in herited classes, following the Python interpreter policy
210 * (mono or multi interpreter...).
212 void PyInterp_base::initialize()
214 MESSAGE("PyInterp_base::initialize()");
217 _history.clear(); // start a new list of user's commands
218 _ith = _history.begin();
226 m=PyImport_ImportModule("codeop"); // used to interpret & compile commands
229 MESSAGE("Problem...");
238 * Create cStringIO to capture stdout and stderr
241 PycStringIO=(PycStringIO_CAPI *)xxxPyCObject_Import("cStringIO", "cStringIO_CAPI");
242 _vout=PycStringIO->NewOutput(128);
243 _verr=PycStringIO->NewOutput(128);
245 // All the initRun outputs are redirected to the standard output (console)
248 // We go out of Python world to enter the C++ world. Release the Python global lock
254 string PyInterp_base::getbanner()
256 MESSAGE("PyInterp_base::getbanner()");
257 string banner = "Python ";
258 banner = banner + Py_GetVersion() + " on " + Py_GetPlatform() ;
259 banner = banner + "\ntype help to get general information on environment\n";
260 return banner.c_str();
263 int PyInterp_base::initRun()
265 MESSAGE("PyInterp_base::initRun()");
266 PySys_SetObject("stderr",_verr);
267 PySys_SetObject("stdout",_vout);
269 PyObject *v = PyObject_CallMethod(_verr,"reset","");
271 v = PyObject_CallMethod(_vout,"reset","");
276 m = PyImport_GetModuleDict();
278 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
279 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
281 MESSAGE(this->getvout());
282 MESSAGE(this->getverr());
287 void PyInterp_base::enter()
289 MESSAGE("PyInterp_base::enter()");
291 PyThreadState_Swap(_tstate);
294 void PyInterp_base::quit()
296 MESSAGE("PyInterp_base::quit()");
300 void PyInterp_base::basicRun(const char *command)
305 code=Py_CompileString((char *)command,"PyInterp_base",Py_file_input);
309 * Caught an error : SyntaxError
316 r = PyEval_EvalCode(code,_g,_g);
321 * Caught an error during execution
332 int PyInterp_base::run(const char *command)
339 ret = this->simpleRun("from Help import *");
340 MESSAGE(this->getvout())
341 MESSAGE(this->getverr())
342 if (ret != 0) return ret;
343 ret = this->simpleRun("import salome");
344 MESSAGE(this->getvout());
345 MESSAGE(this->getverr())
346 if (ret != 0) return ret;
348 ret = this->simpleRun(command);
352 int PyInterp_base::simpleRun(const char *command)
355 PyObject *v,*m,*r,*g;
358 string s_com = command;
360 if (s_com.size() > 0)
362 _history.push_back(s_com);
363 _ith = _history.end();
364 SCRUTE(_history.back());
369 // We come from C++ to enter Python world
370 // We need to acquire the Python global lock
372 // Restore the sub interpreter thread state : this._tstate
373 PyThreadState_Swap(_tstate);
376 Reset redirected outputs before treatment
378 PySys_SetObject("stderr",_verr);
379 PySys_SetObject("stdout",_vout);
381 v = PyObject_CallMethod(_verr,"reset","");
383 v = PyObject_CallMethod(_vout,"reset","");
386 ier=compile_command(command,_g);
388 // Outputs are redirected on standards outputs (console)
389 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
390 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
392 // We go back to the C++ world. Release the lock.
397 static string vout_buffer;
398 static string verr_buffer;
400 char * PyInterp_base::getverr()
402 MESSAGE("PyInterp_base::getverr");
404 v=PycStringIO->cgetvalue(_verr);
405 verr_buffer=PyString_AsString(v);
407 return (char *)verr_buffer.c_str();
410 char * PyInterp_base::getvout()
412 MESSAGE("PyInterp_base::getvout");
414 v=PycStringIO->cgetvalue(_vout);
415 vout_buffer=PyString_AsString(v);
417 return (char *)vout_buffer.c_str();
420 const char * PyInterp_base::getPrevious()
422 MESSAGE("PyInterp_base::getPrevious");
423 if (_ith != _history.begin())
426 return (*_ith).c_str();
429 return BEGIN_HISTORY_PY;
432 const char * PyInterp_base::getNext()
434 MESSAGE("PyInterp_base::getNext");
435 if (_ith != _history.end())
439 if (_ith == _history.end())
440 return TOP_HISTORY_PY;
442 return (*_ith).c_str();