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 SCRUTE(PyInterp_base::salome_shared_modules_module->ob_refcnt);
110 * This function compiles a string (command) and then evaluates it in the dictionnary
111 * context if possible.
114 * 1 : incomplete text
115 * 0 : complete text executed with success
118 int compile_command(const char *command,PyObject *context)
123 m=PyImport_AddModule("codeop");
127 * Fatal error. No way to go on.
132 v= PyObject_CallMethod(m,"compile_command","s",command);
136 * Error encountered. It could be SyntaxError
141 else if (v == Py_None)
144 * Incomplete text we return 1 : we need a complete text to execute
151 * Complete and correct text. We evaluate it.
153 r = PyEval_EvalCode(v,context,context);
158 * Execution error. We return -1
165 * The command has been successfully executed. Return 0
172 * basic constructor here : herited classes constructors must call initalize() method
176 PyInterp_base::PyInterp_base():_tstate(0),_vout(0),_verr(0),_g(0),_atFirst(true)
178 MESSAGE("PyInterp_base::PyInterp_base()");
181 PyInterp_base::~PyInterp_base()
183 MESSAGE("PyInterp_base::~PyInterp_base()");
185 PyThreadState_Swap(_tstate);
186 Py_EndInterpreter(_tstate);
191 * Must be called by herited classes constructors. initialize() calls virtuals methods
192 * initstate & initcontext, not defined here in base class. initstate & initcontext methods
193 * must be implemented in herited classes, following the Python interpreter policy
194 * (mono or multi interpreter...).
196 void PyInterp_base::initialize()
198 MESSAGE("PyInterp_base::initialize()");
201 _history.clear(); // start a new list of user's commands
202 _ith = _history.begin();
210 m=PyImport_ImportModule("codeop"); // used to interpret & compile commands
213 MESSAGE("Problem...");
222 * Create cStringIO to capture stdout and stderr
225 PycStringIO=(PycStringIO_CAPI *)xxxPyCObject_Import("cStringIO", "cStringIO_CAPI");
226 _vout=PycStringIO->NewOutput(128);
227 _verr=PycStringIO->NewOutput(128);
229 // All the initRun outputs are redirected to the standard output (console)
232 // We go out of Python world to enter the C++ world. Release the Python global lock
238 string PyInterp_base::getbanner()
240 MESSAGE("PyInterp_base::getbanner()");
241 string banner = "Python ";
242 banner = banner + Py_GetVersion() + " on " + Py_GetPlatform() ;
243 banner = banner + "\ntype help to get general information on environment\n";
244 return banner.c_str();
247 int PyInterp_base::initRun()
249 MESSAGE("PyInterp_base::initRun()");
250 PySys_SetObject("stderr",_verr);
251 PySys_SetObject("stdout",_vout);
253 PyObject *v = PyObject_CallMethod(_verr,"reset","");
255 v = PyObject_CallMethod(_vout,"reset","");
260 m = PyImport_GetModuleDict();
262 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
263 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
265 MESSAGE(this->getvout());
266 MESSAGE(this->getverr());
271 void PyInterp_base::enter()
273 MESSAGE("PyInterp_base::enter()");
275 PyThreadState_Swap(_tstate);
278 void PyInterp_base::quit()
280 MESSAGE("PyInterp_base::quit()");
284 void PyInterp_base::basicRun(const char *command)
289 code=Py_CompileString((char *)command,"PyInterp_base",Py_file_input);
293 * Caught an error : SyntaxError
300 r = PyEval_EvalCode(code,_g,_g);
305 * Caught an error during execution
316 int PyInterp_base::run(const char *command)
323 ret = this->simpleRun("from Help import *");
324 MESSAGE(this->getvout())
325 MESSAGE(this->getverr())
326 if (ret != 0) return ret;
327 ret = this->simpleRun("import salome");
328 MESSAGE(this->getvout());
329 MESSAGE(this->getverr())
330 if (ret != 0) return ret;
332 ret = this->simpleRun(command);
336 int PyInterp_base::simpleRun(const char *command)
339 PyObject *v,*m,*r,*g;
342 string s_com = command;
344 if (s_com.size() > 0)
346 _history.push_back(s_com);
347 _ith = _history.end();
348 SCRUTE(_history.back());
353 // We come from C++ to enter Python world
354 // We need to acquire the Python global lock
356 // Restore the sub interpreter thread state : this._tstate
357 PyThreadState_Swap(_tstate);
360 Reset redirected outputs before treatment
362 PySys_SetObject("stderr",_verr);
363 PySys_SetObject("stdout",_vout);
365 v = PyObject_CallMethod(_verr,"reset","");
367 v = PyObject_CallMethod(_vout,"reset","");
370 ier=compile_command(command,_g);
372 // Outputs are redirected on standards outputs (console)
373 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
374 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
376 // We go back to the C++ world. Release the lock.
381 static string vout_buffer;
382 static string verr_buffer;
384 char * PyInterp_base::getverr()
386 MESSAGE("PyInterp_base::getverr");
388 v=PycStringIO->cgetvalue(_verr);
389 verr_buffer=PyString_AsString(v);
391 return (char *)verr_buffer.c_str();
394 char * PyInterp_base::getvout()
396 MESSAGE("PyInterp_base::getvout");
398 v=PycStringIO->cgetvalue(_vout);
399 vout_buffer=PyString_AsString(v);
401 return (char *)vout_buffer.c_str();
404 const char * PyInterp_base::getPrevious()
406 MESSAGE("PyInterp_base::getPrevious");
407 if (_ith != _history.begin())
410 return (*_ith).c_str();
413 return BEGIN_HISTORY_PY;
416 const char * PyInterp_base::getNext()
418 MESSAGE("PyInterp_base::getNext");
419 if (_ith != _history.end())
423 if (_ith == _history.end())
424 return TOP_HISTORY_PY;
426 return (*_ith).c_str();