1
/***************************************************************************
2
* (c) Jļæ½rgen Riegel (juergen.riegel@web.de) 2002 *
4
* This file is part of the FreeCAD CAx development system. *
6
* This program is free software; you can redistribute it and/or modify *
7
* it under the terms of the GNU Library General Public License (LGPL) *
8
* as published by the Free Software Foundation; either version 2 of *
9
* the License, or (at your option) any later version. *
10
* for detail see the LICENCE text file. *
12
* FreeCAD is distributed in the hope that it will be useful, *
13
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
14
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
15
* GNU Library General Public License for more details. *
17
* You should have received a copy of the GNU Library General Public *
18
* License along with FreeCAD; if not, write to the Free Software *
19
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 *
22
* Juergen Riegel 2002 *
23
***************************************************************************/
26
#include "PreCompiled.h"
34
#include "Interpreter.h"
38
#include "Exception.h"
39
#include "PyObjectBase.h"
42
char format2[1024]; //Warning! Can't go over 512 characters!!!
43
unsigned int format2_len = 1024;
47
#if PY_VERSION_HEX <= 0x02050000
48
#error "Use Python2.5.x or higher"
52
PyException::PyException(void)
54
PP_Fetch_Error_Text(); /* fetch (and clear) exception */
55
std::string prefix = PP_last_error_type; /* exception name text */
57
std::string error = PP_last_error_info; /* exception data text */
59
// The Python exceptions might be thrown from nested functions, so take
60
// into account not to add the same prefix several times
61
std::string::size_type pos = error.find(prefix);
62
if (pos == std::string::npos)
63
_sErrMsg = prefix + error;
71
_stackTrace = PP_last_error_trace; /* exception traceback text */
73
PyErr_Clear(); // must be called to keep Python interpreter in a valid state (Werner)
77
// ---------------------------------------------------------
79
SystemExitException::SystemExitException()
81
_sErrMsg = "System exit";
84
SystemExitException::SystemExitException(const SystemExitException &inst)
89
// ---------------------------------------------------------
92
InterpreterSingleton::InterpreterSingleton()
97
InterpreterSingleton::~InterpreterSingleton()
103
std::string InterpreterSingleton::runString(const char *sCmd)
105
PyObject *module, *dict, *presult; /* "exec code in d, d" */
107
PyGILStateLocker locker;
108
module = PP_Load_Module("__main__"); /* get module, init python */
110
throw PyException(); /* not incref'd */
111
dict = PyModule_GetDict(module); /* get dict namespace */
113
throw PyException(); /* not incref'd */
116
presult = PyRun_String(sCmd, Py_file_input, dict, dict); /* eval direct */
121
PyObject* repr = PyObject_Repr(presult);
124
std::string ret(PyString_AsString(repr));
130
return std::string();
134
void InterpreterSingleton::systemExit(void)
136
/* This code is taken from the original Python code */
137
PyObject *exception, *value, *tb;
140
PyErr_Fetch(&exception, &value, &tb);
144
if (value == NULL || value == Py_None)
146
if (PyInstance_Check(value)) {
147
/* The error code should be in the `code' attribute. */
148
PyObject *code = PyObject_GetAttrString(value, "code");
152
if (value == Py_None)
155
/* If we failed to dig out the 'code' attribute,
156
just let the else clause below print the error. */
158
if (PyInt_Check(value))
159
exitcode = (int)PyInt_AsLong(value);
161
PyObject_Print(value, stderr, Py_PRINT_RAW);
162
PySys_WriteStderr("\n");
166
/* Restore and clear the exception info, in order to properly decref
167
* the exception, value, and traceback. If we just exit instead,
168
* these leak, which confuses PYTHONDUMPREFS output, and may prevent
169
* some finalizers from running.
171
PyErr_Restore(exception, value, tb);
177
void InterpreterSingleton::runInteractiveString(const char *sCmd)
179
PyObject *module, *dict, *presult; /* "exec code in d, d" */
181
PyGILStateLocker locker;
182
module = PP_Load_Module("__main__"); /* get module, init python */
184
throw PyException(); /* not incref'd */
185
dict = PyModule_GetDict(module); /* get dict namespace */
187
throw PyException(); /* not incref'd */
189
presult = PyRun_String(sCmd, Py_single_input, dict, dict); /* eval direct */
191
if (PyErr_ExceptionMatches(PyExc_SystemExit)) {
193
throw SystemExitException();
195
/* get latest python exception information */
196
/* and print the error to the error output */
197
PyObject *errobj, *errdata, *errtraceback;
198
PyErr_Fetch(&errobj, &errdata, &errtraceback);
200
Exception exc; // do not use PyException since this clears the error indicator
201
if (PyString_Check(errdata))
202
exc.setMessage(PyString_AsString(errdata));
203
PyErr_Restore(errobj, errdata, errtraceback);
204
if (PyErr_Occurred())
212
void InterpreterSingleton::runFile(const char*pxFileName)
214
FileInfo fi(pxFileName);
215
Base::ifstream file(fi, std::ios::in);
221
runString(buf.str().c_str());
224
std::string err = "Unknown file: ";
227
throw Exception(err);
231
bool InterpreterSingleton::loadModule(const char* psModName)
234
//PyBuf ModName(psModName);
237
PyGILStateLocker locker;
238
module = PP_Load_Module(psModName);
246
void InterpreterSingleton::addType(PyTypeObject* Type,PyObject* Module, const char * Name)
248
// NOTE: To finish the initialization of our own type objects we must
249
// call PyType_Ready, otherwise we run into a segmentation fault, later on.
250
// This function is responsible for adding inherited slots from a type's base class.
251
if (PyType_Ready(Type) < 0) return;
252
union PyType_Object pyType = {Type};
253
PyModule_AddObject(Module, Name, pyType.o);
256
void InterpreterSingleton::addPythonPath(const char* Path)
258
PyGILStateLocker locker;
259
PyObject *list = PySys_GetObject("path");
260
PyObject *path = PyString_FromString(Path);
261
PyList_Append(list, path);
263
PySys_SetObject("path", list);
266
const char* InterpreterSingleton::init(int argc,char *argv[])
268
if (!Py_IsInitialized()) {
269
Py_SetProgramName(argv[0]);
270
PyEval_InitThreads();
272
PySys_SetArgv(argc, argv);
273
this->_global = PyEval_SaveThread();
279
int InterpreterSingleton::cleanup(void (*func)(void))
281
return Py_AtExit( func );
284
void InterpreterSingleton::finalize()
287
PyEval_RestoreThread(this->_global);
294
void InterpreterSingleton::runStringArg(const char * psCom,...)
297
va_list namelessVars;
298
va_start(namelessVars, psCom); // Get the "..." vars
299
int len = vsnprintf(format2, format2_len, psCom, namelessVars);
300
va_end(namelessVars);
312
InterpreterSingleton * InterpreterSingleton::_pcSingelton = 0;
314
InterpreterSingleton & InterpreterSingleton::Instance(void)
318
_pcSingelton = new InterpreterSingleton();
319
return *_pcSingelton;
322
void InterpreterSingleton::Destruct(void)
324
// not initialized or double destruct!
325
assert(_pcSingelton);
330
int InterpreterSingleton::runCommandLine(const char *prompt)
332
PyGILStateLocker locker;
333
return PP_Run_Command_Line(prompt);
337
* Runs a member method of an object with no parameter and no return value
338
* void (void). There are other methods to run with returns
340
void InterpreterSingleton::runMethodVoid(PyObject *pobject, const char *method)
342
PyGILStateLocker locker;
343
if (PP_Run_Method(pobject , // object
344
method, // run method
346
0, // so no return object
347
"()") // no arguments
349
throw PyException(/*"Error running InterpreterSingleton::RunMethodVoid()"*/);
353
PyObject* InterpreterSingleton::runMethodObject(PyObject *pobject, const char *method)
357
PyGILStateLocker locker;
358
if (PP_Run_Method(pobject , // object
359
method, // run method
361
&pcO, // return object
362
"()") // no arguments
364
throw PyException(/*"Error runing InterpreterSingleton::RunMethodObject()"*/);
369
void InterpreterSingleton::runMethod(PyObject *pobject, const char *method,
370
const char *resfmt, void *cresult, /* convert to c/c++ */
371
const char *argfmt, ... ) /* convert to python */
373
PyObject *pmeth, *pargs, *presult;
374
va_list argslist; /* "pobject.method(args)" */
375
va_start(argslist, argfmt);
377
PyGILStateLocker locker;
378
pmeth = PyObject_GetAttrString(pobject, method);
379
if (pmeth == NULL) /* get callable object */
380
throw Exception("Error runing InterpreterSingleton::RunMethod() method not defined"); /* bound method? has self */
382
pargs = Py_VaBuildValue(argfmt, argslist); /* args: c->python */
386
throw Exception("InterpreterSingleton::RunMethod() wrong arguments");
389
presult = PyEval_CallObject(pmeth, pargs); /* run interpreter */
393
if (PP_Convert_Result(presult, resfmt, cresult)!= 0) {
394
if ( PyErr_Occurred() )
396
throw Exception("Error runing InterpreterSingleton::RunMethod() exception in called method");
401
void InterpreterSingleton::dbgObserveFile(const char* sFileName)
404
_cDebugFileName = sFileName;
406
_cDebugFileName = "";
409
void InterpreterSingleton::dbgSetBreakPoint(unsigned int /*uiLineNumber*/)
414
void InterpreterSingleton::dbgUnsetBreakPoint(unsigned int /*uiLineNumber*/)
419
void InterpreterSingleton::dbgStep(void)
424
const std::string InterpreterSingleton::strToPython(const char* Str)
429
while (*It != '\0') {
449
// --------------------------------------------------------------------
451
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
452
namespace Swig_python { extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); }
454
namespace Swig_1_3_25 { extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); }
455
namespace Swig_1_3_33 { extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); }
456
namespace Swig_1_3_36 { extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); }
457
namespace Swig_1_3_38 { extern int createSWIGPointerObj_T(const char* TypeName, void* obj, PyObject** ptr, int own); }
459
PyObject* InterpreterSingleton::createSWIGPointerObj(const char* TypeName, void* Pointer, int own)
463
PyGILStateLocker locker;
464
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
465
result = Swig_python::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own);
466
if (result == 0) return proxy;
468
result = Swig_1_3_25::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own);
469
if (result == 0) return proxy;
470
result = Swig_1_3_33::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own);
471
if (result == 0) return proxy;
472
result = Swig_1_3_36::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own);
473
if (result == 0) return proxy;
474
result = Swig_1_3_38::createSWIGPointerObj_T(TypeName, Pointer, &proxy, own);
475
if (result == 0) return proxy;
477
// none of the SWIG's succeeded
478
throw Base::Exception("No SWIG wrapped library loaded");
481
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
482
namespace Swig_python { extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); }
484
namespace Swig_1_3_25 { extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); }
485
namespace Swig_1_3_33 { extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); }
486
namespace Swig_1_3_36 { extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); }
487
namespace Swig_1_3_38 { extern int convertSWIGPointerObj_T(const char* TypeName, PyObject* obj, void** ptr, int flags); }
489
bool InterpreterSingleton::convertSWIGPointerObj(const char* TypeName, PyObject* obj, void** ptr, int flags)
492
PyGILStateLocker locker;
493
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
494
result = Swig_python::convertSWIGPointerObj_T(TypeName, obj, ptr, flags);
495
if (result == 0) return true;
497
result = Swig_1_3_25::convertSWIGPointerObj_T(TypeName, obj, ptr, flags);
498
if (result == 0) return true;
499
result = Swig_1_3_33::convertSWIGPointerObj_T(TypeName, obj, ptr, flags);
500
if (result == 0) return true;
501
result = Swig_1_3_36::convertSWIGPointerObj_T(TypeName, obj, ptr, flags);
502
if (result == 0) return true;
503
result = Swig_1_3_38::convertSWIGPointerObj_T(TypeName, obj, ptr, flags);
504
if (result == 0) return true;
506
// none of the SWIG's succeeded
507
throw Base::Exception("No SWIG wrapped library loaded");
510
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
511
namespace Swig_python { extern void cleanupSWIG_T(const char* TypeName); }
513
namespace Swig_1_3_25 { extern void cleanupSWIG_T(const char* TypeName); }
514
namespace Swig_1_3_33 { extern void cleanupSWIG_T(const char* TypeName); }
515
namespace Swig_1_3_36 { extern void cleanupSWIG_T(const char* TypeName); }
516
namespace Swig_1_3_38 { extern void cleanupSWIG_T(const char* TypeName); }
518
void InterpreterSingleton::cleanupSWIG(const char* TypeName)
520
PyGILStateLocker locker;
521
#if (defined(HAVE_SWIG) && (HAVE_SWIG == 1))
522
Swig_python::cleanupSWIG_T(TypeName);
524
Swig_1_3_25::cleanupSWIG_T(TypeName);
525
Swig_1_3_33::cleanupSWIG_T(TypeName);
526
Swig_1_3_36::cleanupSWIG_T(TypeName);
527
Swig_1_3_38::cleanupSWIG_T(TypeName);