// CPython.cpp
#include "stdafx.h"
#include "CFUtils.h"
#include "CThreads.h"
#include <Python/Python.h>
#include "CPython.h"
#define kEmbeddedModuleName "emb"
#define kCustomPrintFuncName "custom_print"
static PyObject* emb_print(PyObject *self, PyObject *args)
{
PyObject *resultObjP = NULL;
const char *utf8_strZ = NULL;
if (PyArg_ParseTuple(args, "s", &utf8_strZ)) {
Log(utf8_strZ, false);
Py_INCREF(Py_None);
resultObjP = Py_None;
}
return resultObjP;
}
static const PyMethodDef EmbMethods[] = {
{kCustomPrintFuncName, emb_print, METH_VARARGS, "Calls custom print function."},
{NULL, NULL, 0, NULL}
};
static const char *s_RedirectPrint =
"import " kEmbeddedModuleName "\n"
"import sys\n"
"\n"
"class CustomPrintClass:\n"
" def write(self, stuff):\n"
" " kEmbeddedModuleName "." kCustomPrintFuncName "(stuff)\n"
"\n"
"sys.stdout = CustomPrintClass()\n"
"sys.stderr = CustomPrintClass()\n"
"\n";
OSStatus CPython_PreAlloc(const char *utf8Z)
{
OSStatus err = noErr;
PyObject *pyObjectP = NULL;
Py_SetProgramName(const_cast<char *>(utf8Z));
Py_Initialize();
pyObjectP = Py_InitModule(kEmbeddedModuleName, const_cast<PyMethodDef*>(EmbMethods));
ERR_NULL(pyObjectP, tsmUnsupScriptLanguageErr);
// don't DECREF this object?? leave it hanging?
ERR(PyRun_SimpleString(s_RedirectPrint));
return err;
}
void CPython_PostDispose()
{
Py_Finalize();
}
void CPython_Test()
{
CCritical sc(GetSprintfMutex());
Log("---Python START:");
PyRun_SimpleString(
"from time import time, ctime\n"
"print 'Today is', ctime(time())\n");
Log("---Python END:");
}