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
12 #include "PyInterp_base.h"
13 #include "utilities.h"
16 #include <cStringIO.h>
20 extern "C" PyObject * PyEval_EvalCode(PyObject *co, PyObject *g, PyObject *l);
22 static PyThreadState *savedThreadState = NULL;
25 * We have our own routines which are identical to the SIP routines
26 * to not depend from SIP software evolutions
29 extern "C" void salomeAcquireLock()
31 MESSAGE("salomeAcquireLock");
32 PyEval_RestoreThread(savedThreadState);
33 savedThreadState = NULL;
36 extern "C" void salomeReleaseLock()
38 MESSAGE("salomeReleaseLock");
39 savedThreadState = PyEval_SaveThread();
42 extern "C" int salomeCondAcquireLock()
44 MESSAGE("salomeCondAcquireLock");
45 if(savedThreadState != NULL)
48 * If savedThreadState is not NULL, Python global lock is not already acquired
50 * and return 1 to the caller
53 //MESSAGE("We got it (the lock)");
57 * If savedThreadState is NULL, Python global lock is already acquired
58 * We don't acquire or release it
59 * We return 0 to the caller
60 * CAUTION : it's only true when there is no event programming running (Tkinter, PyQt)
65 extern "C" void salomeCondReleaseLock(int rellock)
67 MESSAGE("salomeCondReleaseLock");
72 // main python interpreter
74 PyThreadState *PyInterp_base::_gtstate=0; // force 0 before execution
75 int PyInterp_base::_argc=1;
76 char* PyInterp_base::_argv[] = {""};
78 PyObject *PyInterp_base::builtinmodule=NULL;
79 PyObject *PyInterp_base::salome_shared_modules_module=NULL;
83 SCRUTE(PyInterp_base::_gtstate);
84 if (PyInterp_base::_gtstate) return;
85 Py_Initialize(); // Initialize the interpreter
86 PyEval_InitThreads(); // Create (and acquire) the interpreter lock
87 PySys_SetArgv(PyInterp_base::_argc,PyInterp_base::_argv); // initialize sys.argv
88 PyInterp_base::_gtstate = PyThreadState_Get();
89 SCRUTE(PyInterp_base::_gtstate);
92 // * Import __builtin__ module and store it to use it with all sub-interpreters
93 // * This hack could be used with event programming (PyQt) to avoid errors
94 // * encountered with incoherent builtins
97 // PyInterp_base::builtinmodule =PyImport_ImportModule("__builtin__");
98 // SCRUTE(PyInterp_base::builtinmodule->ob_refcnt);
101 * Import salome_shared_modules module and store it to use it with all sub-interpreters
104 PyInterp_base::salome_shared_modules_module =PyImport_ImportModule("salome_shared_modules");
105 if(PyInterp_base::salome_shared_modules_module == NULL){
106 MESSAGE("init_python: problem with salome_shared_modules import");
112 SCRUTE(PyInterp_base::salome_shared_modules_module->ob_refcnt);
117 * This function compiles a string (command) and then evaluates it in the dictionnary
118 * context if possible.
121 * 1 : incomplete text
122 * 0 : complete text executed with success
125 int compile_command(const char *command,PyObject *context)
130 m=PyImport_AddModule("codeop");
134 * Fatal error. No way to go on.
139 v= PyObject_CallMethod(m,"compile_command","s",command);
143 * Error encountered. It should be SyntaxError
144 * so we don't write out traceback
146 PyObject *exception,*value,*tb;
147 PyErr_Fetch(&exception, &value, &tb);
148 PyErr_NormalizeException(&exception, &value, &tb);
149 PyErr_Display(exception, value, NULL);
150 Py_XDECREF(exception);
156 else if (v == Py_None)
159 * Incomplete text we return 1 : we need a complete text to execute
166 * Complete and correct text. We evaluate it.
168 r = PyEval_EvalCode(v,context,context);
173 * Execution error. We return -1
180 * The command has been successfully executed. Return 0
187 * basic constructor here : herited classes constructors must call initalize() method
191 PyInterp_base::PyInterp_base():_tstate(0),_vout(0),_verr(0),_g(0),_atFirst(true)
193 MESSAGE("PyInterp_base::PyInterp_base()");
196 PyInterp_base::~PyInterp_base()
198 MESSAGE("PyInterp_base::~PyInterp_base()");
200 PyThreadState_Swap(_tstate);
201 Py_EndInterpreter(_tstate);
206 * Must be called by herited classes constructors. initialize() calls virtuals methods
207 * initstate & initcontext, not defined here in base class. initstate & initcontext methods
208 * must be implemented in herited classes, following the Python interpreter policy
209 * (mono or multi interpreter...).
211 void PyInterp_base::initialize()
213 MESSAGE("PyInterp_base::initialize()");
216 _history.clear(); // start a new list of user's commands
217 _ith = _history.begin();
225 m=PyImport_ImportModule("codeop"); // used to interpret & compile commands
228 MESSAGE("Problem...");
237 * Create cStringIO to capture stdout and stderr
240 PycStringIO=(PycStringIO_CAPI *)xxxPyCObject_Import("cStringIO", "cStringIO_CAPI");
241 _vout=PycStringIO->NewOutput(128);
242 _verr=PycStringIO->NewOutput(128);
244 // All the initRun outputs are redirected to the standard output (console)
247 // We go out of Python world to enter the C++ world. Release the Python global lock
253 string PyInterp_base::getbanner()
255 MESSAGE("PyInterp_base::getbanner()");
256 string banner = "Python ";
257 banner = banner + Py_GetVersion() + " on " + Py_GetPlatform() ;
258 banner = banner + "\ntype help to get general information on environment\n";
259 return banner.c_str();
262 int PyInterp_base::initRun()
264 MESSAGE("PyInterp_base::initRun()");
265 PySys_SetObject("stderr",_verr);
266 PySys_SetObject("stdout",_vout);
268 PyObject *v = PyObject_CallMethod(_verr,"reset","");
270 v = PyObject_CallMethod(_vout,"reset","");
275 m = PyImport_GetModuleDict();
277 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
278 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
280 MESSAGE(this->getvout());
281 MESSAGE(this->getverr());
286 void PyInterp_base::enter()
288 MESSAGE("PyInterp_base::enter()");
290 PyThreadState_Swap(_tstate);
293 void PyInterp_base::quit()
295 MESSAGE("PyInterp_base::quit()");
299 void PyInterp_base::basicRun(const char *command)
304 code=Py_CompileString((char *)command,"PyInterp_base",Py_file_input);
308 * Caught an error : SyntaxError
315 r = PyEval_EvalCode(code,_g,_g);
320 * Caught an error during execution
331 int PyInterp_base::run(const char *command)
338 ret = this->simpleRun("from Help import *");
339 MESSAGE(this->getvout())
340 MESSAGE(this->getverr())
341 if (ret != 0) return ret;
342 ret = this->simpleRun("import salome");
343 MESSAGE(this->getvout());
344 MESSAGE(this->getverr())
345 if (ret != 0) return ret;
347 ret = this->simpleRun(command);
351 int PyInterp_base::simpleRun(const char *command)
354 PyObject *v,*m,*r,*g;
357 string s_com = command;
359 if (s_com.size() > 0)
361 _history.push_back(s_com);
362 _ith = _history.end();
363 SCRUTE(_history.back());
368 // We come from C++ to enter Python world
369 // We need to acquire the Python global lock
371 // Restore the sub interpreter thread state : this._tstate
372 PyThreadState_Swap(_tstate);
375 Reset redirected outputs before treatment
377 PySys_SetObject("stderr",_verr);
378 PySys_SetObject("stdout",_vout);
380 v = PyObject_CallMethod(_verr,"reset","");
382 v = PyObject_CallMethod(_vout,"reset","");
385 ier=compile_command(command,_g);
387 // Outputs are redirected on standards outputs (console)
388 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
389 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
391 // We go back to the C++ world. Release the lock.
396 static string vout_buffer;
397 static string verr_buffer;
399 char * PyInterp_base::getverr()
401 MESSAGE("PyInterp_base::getverr");
403 v=PycStringIO->cgetvalue(_verr);
404 verr_buffer=PyString_AsString(v);
406 return (char *)verr_buffer.c_str();
409 char * PyInterp_base::getvout()
411 MESSAGE("PyInterp_base::getvout");
413 v=PycStringIO->cgetvalue(_vout);
414 vout_buffer=PyString_AsString(v);
416 return (char *)vout_buffer.c_str();
419 const char * PyInterp_base::getPrevious()
421 MESSAGE("PyInterp_base::getPrevious");
422 if (_ith != _history.begin())
425 return (*_ith).c_str();
428 return BEGIN_HISTORY_PY;
431 const char * PyInterp_base::getNext()
433 MESSAGE("PyInterp_base::getNext");
434 if (_ith != _history.end())
438 if (_ith == _history.end())
439 return TOP_HISTORY_PY;
441 return (*_ith).c_str();