1 // Copyright (C) 2007-2008 CEA/DEN, EDF R&D, OPEN CASCADE
3 // Copyright (C) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
4 // CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
6 // This library is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU Lesser General Public
8 // License as published by the Free Software Foundation; either
9 // version 2.1 of the License.
11 // This library is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // Lesser General Public License for more details.
16 // You should have received a copy of the GNU Lesser General Public
17 // License along with this library; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 // See http://www.salome-platform.org/ or email : webmaster.salome@opencascade.com
22 // File : PyInterp_Interp.cxx
23 // Author : Christian CAREMOLI, Paul RASCLE, EDF
26 #include "PyInterp_Interp.h" // !!! WARNING !!! THIS INCLUDE MUST BE THE VERY FIRST !!!
28 #include <cStringIO.h>
29 #include <structmember.h>
35 #define TOP_HISTORY_PY "--- top of history ---"
36 #define BEGIN_HISTORY_PY "--- begin of history ---"
40 \brief Python GIL wrapper.
44 \brief Constructor. Automatically acquires GIL.
45 \param theThreadState python thread state
47 PyLockWrapper::PyLockWrapper(PyThreadState* theThreadState):
48 myThreadState(theThreadState),
51 if (myThreadState->interp == PyInterp_Interp::_interp)
52 _savestate = PyGILState_Ensure();
54 PyEval_AcquireThread(myThreadState);
58 \brief Desstructor. Automatically releases GIL.
60 PyLockWrapper::~PyLockWrapper()
62 if (myThreadState->interp == PyInterp_Interp::_interp)
63 PyGILState_Release(_savestate);
65 PyEval_ReleaseThread(myThreadState);
69 \brief Get Python GIL wrapper.
70 \return GIL lock wrapper (GIL is automatically acquired here)
72 PyLockWrapper PyInterp_Interp::GetLockWrapper()
78 The following functions are used to hook the Python
83 PyStdOut_dealloc(PyStdOut *self)
89 PyStdOut_write(PyStdOut *self, PyObject *args)
93 if (!PyArg_ParseTuple(args, "t#:write",&c, &l))
102 self->_cb(self->_data,c);
108 static PyMethodDef PyStdOut_methods[] = {
109 {"write", (PyCFunction)PyStdOut_write, METH_VARARGS,
110 PyDoc_STR("write(string) -> None")},
111 {NULL, NULL} /* sentinel */
114 static PyMemberDef PyStdOut_memberlist[] = {
115 {"softspace", T_INT, offsetof(PyStdOut, softspace), 0,
116 "flag indicating that a space needs to be printed; used by print"},
117 {NULL} /* Sentinel */
120 static PyTypeObject PyStdOut_Type = {
121 /* The ob_type field must be initialized in the module init function
122 * to be portable to Windows without using C++. */
123 PyObject_HEAD_INIT(NULL)
126 sizeof(PyStdOut), /*tp_basicsize*/
129 (destructor)PyStdOut_dealloc, /*tp_dealloc*/
136 0, /*tp_as_sequence*/
141 PyObject_GenericGetAttr, /*tp_getattro*/
142 /* softspace is writable: we must supply tp_setattro */
143 PyObject_GenericSetAttr, /* tp_setattro */
145 Py_TPFLAGS_DEFAULT, /*tp_flags*/
149 0, /*tp_richcompare*/
150 0, /*tp_weaklistoffset*/
153 PyStdOut_methods, /*tp_methods*/
154 PyStdOut_memberlist, /*tp_members*/
168 #define PyStdOut_Check(v) ((v)->ob_type == &PyStdOut_Type)
170 static PyStdOut* newPyStdOut( bool iscerr )
173 self = PyObject_New(PyStdOut, &PyStdOut_Type);
178 self->_iscerr = iscerr;
183 \class PyInterp_Interp
184 \brief Generic embedded Python interpreter.
187 int PyInterp_Interp::_argc = 1;
188 char* PyInterp_Interp::_argv[] = {""};
189 PyObject* PyInterp_Interp::builtinmodule = NULL;
190 PyThreadState* PyInterp_Interp::_gtstate = NULL;
191 PyInterpreterState* PyInterp_Interp::_interp = NULL;
194 \brief Basic constructor.
196 After construction the interpreter instance successor classes
197 must call virtual method initalize().
199 PyInterp_Interp::PyInterp_Interp():
200 _tstate(0), _vout(0), _verr(0), _g(0)
207 PyInterp_Interp::~PyInterp_Interp()
212 \brief Initialize embedded interpreter.
214 This method shoud be called after construction of the interpreter.
215 The method initialize() calls virtuals methods
216 - initPython() to initialize global Python interpreter
217 - initState() to initialize embedded interpreter state
218 - initContext() to initialize interpreter internal context
219 - initRun() to prepare interpreter for running commands
220 which should be implemented in the successor classes, according to the
221 embedded Python interpreter policy (mono or multi interpreter, etc).
223 void PyInterp_Interp::initialize()
225 _history.clear(); // start a new list of user's commands
226 _ith = _history.begin();
229 // Here the global lock is released
233 PyLockWrapper aLock = GetLockWrapper();
237 // used to interpret & compile commands
238 PyObjWrapper m(PyImport_ImportModule("codeop"));
244 // Create python objects to capture stdout and stderr
245 _vout=(PyObject*)newPyStdOut( false ); // stdout
246 _verr=(PyObject*)newPyStdOut( true ); // stderr
248 // All the initRun outputs are redirected to the standard output (console)
253 \brief Initialize Python interpreter.
255 In case if Python is not initialized, it sets program name, initializes the interpreter, sets program arguments,
257 Otherwise, it just obtains the global interpreter and thread states. This is important for light SALOME configuration,
258 as in full SALOME this is done at SalomeApp level.
259 \sa SalomeApp_PyInterp class
261 void PyInterp_Interp::initPython()
263 if (!Py_IsInitialized()){
264 // Python is not initialized
265 Py_SetProgramName(_argv[0]);
266 Py_Initialize(); // Initialize the interpreter
267 PySys_SetArgv(_argc, _argv);
268 PyEval_InitThreads(); // Create (and acquire) the interpreter lock
271 if ( _interp == NULL )
272 _interp = PyThreadState_Get()->interp;
273 if (PyType_Ready(&PyStdOut_Type) < 0) {
276 if ( _gtstate == NULL )
277 _gtstate = PyEval_SaveThread(); // Release global thread state
281 \brief Get embedded Python interpreter banner.
282 \return banner string
284 std::string PyInterp_Interp::getbanner()
286 // Should we take the lock ?
287 // PyEval_RestoreThread(_tstate);
288 std::string aBanner("Python ");
289 aBanner = aBanner + Py_GetVersion() + " on " + Py_GetPlatform() ;
290 aBanner = aBanner + "\ntype help to get general information on environment\n";
291 //PyEval_SaveThread();
296 \brief Initialize run command.
298 This method is used to prepare interpreter for running
301 \return \c true on success and \c false on error
303 bool PyInterp_Interp::initRun()
306 // probably all below code isn't required
309 PySys_SetObject("stderr",_verr);
310 PySys_SetObject("stdout",_vout);
312 //PyObject *m = PyImport_GetModuleDict();
314 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
315 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
321 \brief Compile Python command and evaluate it in the
322 python dictionary context if possible.
324 \param command Python command string
325 \param context Python context (dictionary)
326 \return -1 on fatal error, 1 if command is incomplete and 0
327 if command is executed successfully
329 static int compile_command(const char *command,PyObject *context)
331 PyObject *m = PyImport_AddModule("codeop");
332 if(!m) { // Fatal error. No way to go on.
336 PyObjWrapper v(PyObject_CallMethod(m,"compile_command","s",command));
338 // Error encountered. It should be SyntaxError,
339 //so we don't write out traceback
340 PyObjWrapper exception, value, tb;
341 PyErr_Fetch(&exception, &value, &tb);
342 PyErr_NormalizeException(&exception, &value, &tb);
343 PyErr_Display(exception, value, NULL);
346 else if (v == Py_None) {
347 // Incomplete text we return 1 : we need a complete text to execute
351 // Complete and correct text. We evaluate it.
352 //#if PY_VERSION_HEX < 0x02040000 // python version earlier than 2.4.0
353 // PyObjWrapper r(PyEval_EvalCode(v,context,context));
355 PyObjWrapper r(PyEval_EvalCode((PyCodeObject *)(void *)v,context,context));
358 // Execution error. We return -1
362 // The command has been successfully executed. Return 0
368 \brief Run Python command.
369 \param command Python command
370 \return command status
372 int PyInterp_Interp::run(const char *command)
375 return simpleRun(command);
379 \brief Run Python command (used internally).
380 \param command Python command
381 \param addToHistory if \c true (default), the command is added to the commands history
382 \return command status
384 int PyInterp_Interp::simpleRun(const char *command, const bool addToHistory)
386 if( addToHistory && strcmp(command,"") != 0 ) {
387 _history.push_back(command);
388 _ith = _history.end();
391 // We come from C++ to enter Python world
392 // We need to acquire the Python global lock
393 //PyLockWrapper aLock(_tstate); // san - lock is centralized now
395 // Reset redirected outputs before treatment
396 PySys_SetObject("stderr",_verr);
397 PySys_SetObject("stdout",_vout);
399 int ier = compile_command(command,_g);
401 // Outputs are redirected on standards outputs (console)
402 PySys_SetObject("stdout",PySys_GetObject("__stdout__"));
403 PySys_SetObject("stderr",PySys_GetObject("__stderr__"));
409 \brief Get previous command in the commands history.
410 \return previous command
412 const char * PyInterp_Interp::getPrevious()
414 if(_ith != _history.begin()){
416 return (*_ith).c_str();
419 return BEGIN_HISTORY_PY;
423 \brief Get next command in the commands history.
426 const char * PyInterp_Interp::getNext()
428 if(_ith != _history.end()){
431 if (_ith == _history.end())
432 return TOP_HISTORY_PY;
434 return (*_ith).c_str();
438 \brief Set Python standard output device hook.
439 \param cb callback function
440 \param data callback function parameters
442 void PyInterp_Interp::setvoutcb(PyOutChanged* cb, void* data)
444 ((PyStdOut*)_vout)->_cb=cb;
445 ((PyStdOut*)_vout)->_data=data;
449 \brief Set Python standard error device hook.
450 \param cb callback function
451 \param data callback function parameters
453 void PyInterp_Interp::setverrcb(PyOutChanged* cb, void* data)
455 ((PyStdOut*)_verr)->_cb=cb;
456 ((PyStdOut*)_verr)->_data=data;