43 DECLARE_EXPORT PyThreadState* PythonInterpreter::mainThreadState = NULL;
48 return encoding.c_str();
55 if(!Py_IsInitialized())
60 #if PY_VERSION_HEX > 0x02060600
61 if (argc>0) PySys_SetArgvEx(argc, argv, 0);
65 mainThreadState = PyEval_SaveThread();
69 PyGILState_STATE state = PyGILState_Ensure();
72 module = Py_InitModule3(
"frepple", NULL,
"Access to the frePPLe library");
75 PyGILState_Release(state);
99 "Prints a string to the frePPLe log file.",
false);
101 "import frepple, sys\n"
103 "\tdef write(self,str):\n"
104 "\t\tfrepple.log(str)\n"
105 "sys.stdout = redirect()\n"
106 "sys.stderr = redirect()"
110 PyObject* localemodule = PyImport_ImportModule(
"locale");
113 PyGILState_Release(state);
118 PyObject* moduledict = PyModule_GetDict(localemodule);
119 PyObject* func = PyDict_GetItemString(moduledict,
"getpreferredencoding");
122 PyGILState_Release(state);
123 throw RuntimeException(
"Can't find 'getpreferredencoding' Python function");
125 PyObject* retval = PyEval_CallObject(func, NULL);
128 encoding = PyString_AsString(retval);
131 Py_XDECREF(localemodule);
135 PyGILState_Release(state);
145 if (!mainThreadState)
return;
148 PyEval_AcquireLock();
149 PyEval_RestoreThread(mainThreadState);
157 PyThreadState * myThreadState = PyGILState_GetThisThreadState();
158 if (myThreadState)
return;
161 PyThreadState *tcur = PyThreadState_New(PyInterpreterState_Head());
165 PyEval_RestoreThread(tcur);
166 PyEval_ReleaseLock();
173 PyThreadState * tcur = PyGILState_GetThisThreadState();
177 PyEval_RestoreThread(tcur);
178 PyThreadState_Clear(tcur);
179 PyThreadState_DeleteCurrent();
186 PyGILState_STATE state = PyGILState_Ensure();
189 PyObject *m = PyImport_AddModule(
"__main__");
193 PyGILState_Release(state);
196 PyObject *d = PyModule_GetDict(m);
200 PyGILState_Release(state);
206 PyObject *v = PyRun_String(cmd, Py_file_input, d, d);
212 PyGILState_Release(state);
216 if (Py_FlushLine()) PyErr_Clear();
219 PyGILState_Release(state);
231 for (string::size_type pos = filename.find_first_of(
"'", 0);
233 pos = filename.find_first_of(
"'", pos))
235 filename.replace(pos,1,
"\\'",2);
238 string cmd =
"execfile(ur'" + filename +
"')\n";
244 const char* name, PyCFunction method,
int flags,
const char* doc,
bool lock
250 string *leakingName =
new string(name);
251 string *leakingDoc =
new string(doc);
252 PyMethodDef *newMethod =
new PyMethodDef;
253 newMethod->ml_name = leakingName->c_str();
254 newMethod->ml_meth = method;
255 newMethod->ml_flags = flags;
256 newMethod->ml_doc = leakingDoc->c_str();
259 PyGILState_STATE state;
260 if (lock) state = PyGILState_Ensure();
263 PyObject* mod = PyString_FromString(
"frepple");
266 if (lock) PyGILState_Release(state);;
269 PyObject* func = PyCFunction_NewEx(newMethod, NULL, mod);
273 if (lock) PyGILState_Release(state);
278 PyObject* moduledict = PyModule_GetDict(module);
282 if (lock) PyGILState_Release(state);
285 if (PyDict_SetItemString(moduledict ,leakingName->c_str(), func) < 0)
288 if (lock) PyGILState_Release(state);
294 if (lock) PyGILState_Release(state);
299 (
const char* c, PyCFunctionWithKeywords f,
int i,
const char* d,
bool b)
301 registerGlobalMethod(c, reinterpret_cast<PyCFunction>(f), i | METH_KEYWORDS, d, b);
305 PyObject* PythonInterpreter::python_log(PyObject *
self, PyObject *args)
309 int ok = PyArg_ParseTuple(args,
"s:log", &data);
310 if (!ok)
return NULL;
317 return Py_BuildValue(
"");
322 const PyTypeObject PythonType::PyTypeObjectTemplate =
324 PyObject_HEAD_INIT(NULL)
326 "frepple.unspecified",
338 reinterpret_cast<hashfunc
>(_Py_HashPointer),
344 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
378 #ifdef HAVE_LOCALTIME_R
380 localtime_r(&ticks, &t);
382 struct tm t = *localtime(&ticks);
384 obj = PyDateTime_FromDateAndTime(t.tm_year+1900, t.tm_mon+1, t.tm_mday,
385 t.tm_hour, t.tm_min, t.tm_sec, 0);
392 if (PyDateTime_Check(obj))
394 PyDateTime_GET_YEAR(obj),
395 PyDateTime_GET_MONTH(obj),
396 PyDateTime_GET_DAY(obj),
397 PyDateTime_DATE_GET_HOUR(obj),
398 PyDateTime_DATE_GET_MINUTE(obj),
399 PyDateTime_DATE_GET_SECOND(obj)
401 else if (PyDate_Check(obj))
403 PyDateTime_GET_YEAR(obj),
404 PyDateTime_GET_MONTH(obj),
405 PyDateTime_GET_DAY(obj)
407 else if (PyString_Check(obj))
409 if (PyUnicode_Check(obj))
412 const_cast<PyObject*&
>(obj) =
415 return Date(PyString_AsString(PyObject_Str(obj)));
419 "Invalid data type. Expecting datetime.date, datetime.datetime or string"
426 obj = p ?
static_cast<PyObject*
>(p) : Py_None;
436 table =
new PyTypeObject(PyTypeObjectTemplate);
437 table->tp_basicsize = base_size;
444 for (vector<PythonType*>::const_iterator i =
table.begin(); i !=
table.end(); ++i)
445 if (**i==*t)
return *i;
449 table.push_back(cachedTypePtr);
450 return cachedTypePtr;
459 PyObject *filearg = NULL;
461 if (!PyArg_ParseTuple(args,
"|cO:toXML", &mode, &filearg))
470 else if (mode ==
'P')
472 else if (mode ==
'D')
485 if (PyFile_Check(filearg))
488 return PyFile_WriteString(ch.str().c_str(), filearg) ?
510 (
const char* method_name, PyCFunction f,
int flags,
const char* doc )
512 unsigned short i = 0;
515 if (!table->tp_methods)
517 table->tp_methods =
new PyMethodDef[methodArraySize];
521 while (table->tp_methods[i].ml_name) i++;
522 if (i % methodArraySize == methodArraySize - 1)
525 PyMethodDef* tmp =
new PyMethodDef[i + 1 + methodArraySize];
526 for(
unsigned short j = 0; j < i; j++)
527 tmp[j] = table->tp_methods[j];
528 delete [] table->tp_methods;
529 table->tp_methods = tmp;
534 table->tp_methods[i].ml_name = method_name;
535 table->tp_methods[i].ml_meth = f;
536 table->tp_methods[i].ml_flags = flags;
537 table->tp_methods[i].ml_doc = doc;
540 table->tp_methods[++i].ml_name = NULL;
541 table->tp_methods[i].ml_meth = NULL;
542 table->tp_methods[i].ml_flags = 0;
543 table->tp_methods[i].ml_doc = NULL;
548 (
const char* c, PyCFunctionWithKeywords f,
int i,
const char* d)
550 addMethod(c, reinterpret_cast<PyCFunction>(f), i | METH_KEYWORDS, d);
557 PyGILState_STATE state = PyGILState_Ensure();
558 if (PyType_Ready(table) < 0)
560 PyGILState_Release(state);
561 throw RuntimeException(
string(
"Can't register python type ") + table->tp_name);
564 int result = PyModule_AddObject(
567 reinterpret_cast<PyObject*>(table)
569 PyGILState_Release(state);
584 catch (
const exception& e)
585 {PyErr_SetString(PyExc_Exception, e.what());}
587 {PyErr_SetString(PyExc_Exception,
"Unidentified exception");}
601 PyGILState_STATE pythonstate = PyGILState_Ensure();
602 func = PyRun_String(n.c_str(), Py_eval_input,
603 PyEval_GetGlobals(), PyEval_GetLocals() );
606 PyGILState_Release(pythonstate);
607 throw DataException(
"Python function '" + n +
"' not defined");
609 if (!PyCallable_Check(func))
611 PyGILState_Release(pythonstate);
612 throw DataException(
"Python object '" + n +
"' is not a function");
617 PyGILState_Release(pythonstate);
623 if (!p || p == Py_None)
630 if (!PyCallable_Check(p))
634 PyGILState_STATE pythonstate = PyGILState_Ensure();
636 p = PyRun_String(n.c_str(), Py_eval_input,
637 PyEval_GetGlobals(), PyEval_GetLocals() );
640 PyGILState_Release(pythonstate);
641 throw DataException(
"Python function '" + n +
"' not defined");
643 if (!PyCallable_Check(p))
645 PyGILState_Release(pythonstate);
646 throw DataException(
"Python object '" + n +
"' is not a function");
648 PyGILState_Release(pythonstate);
660 PyGILState_STATE pythonstate = PyGILState_Ensure();
661 PyObject* result = PyEval_CallFunction(func,
"()");
664 logger <<
"Error: Exception caught when calling Python function '"
665 << (func ? PyEval_GetFuncName(func) :
"NULL") <<
"'" << endl;
666 if (PyErr_Occurred()) PyErr_PrintEx(0);
668 PyGILState_Release(pythonstate);
676 PyGILState_STATE pythonstate = PyGILState_Ensure();
677 PyObject* result = PyEval_CallFunction(func,
"(O)", p);
680 logger <<
"Error: Exception caught when calling Python function '"
681 << (func ? PyEval_GetFuncName(func) :
"NULL") <<
"'" << endl;
682 if (PyErr_Occurred()) PyErr_PrintEx(0);
684 PyGILState_Release(pythonstate);
692 PyGILState_STATE pythonstate = PyGILState_Ensure();
693 PyObject* result = PyEval_CallFunction(func,
"(OO)", p, q);
696 logger <<
"Error: Exception caught when calling Python function '"
697 << (func ? PyEval_GetFuncName(func) :
"NULL") <<
"'" << endl;
698 if (PyErr_Occurred()) PyErr_PrintEx(0);
700 PyGILState_Release(pythonstate);
709 if (!PyString_Check(name))
711 PyErr_Format(PyExc_TypeError,
712 "attribute name must be string, not '%s'",
713 name->ob_type->tp_name);
718 if (result)
return result;
720 if (PyErr_Occurred())
return NULL;
726 return PyObject_GenericGetAttr(
self,name);
741 if (!PyString_Check(name))
743 PyErr_Format(PyExc_TypeError,
744 "attribute name must be string, not '%s'",
745 name->ob_type->tp_name);
754 if (!result)
return 0;
757 if (!PyErr_Occurred())
758 PyErr_Format(PyExc_AttributeError,
759 "attribute '%s' on '%s' can't be updated",
760 PyString_AsString(name),
self->ob_type->tp_name);