Python: Difference between revisions
Jump to navigation
Jump to search
Created page with "<pre> // CPython.cpp #include "stdafx.h" #include "CFUtils.h" #include <Python/Python.h> #include "CPython.h" static PyObject* emb_print(PyObject *self, PyObject *args) { Lo..." |
No edit summary |
||
| Line 17: | Line 17: | ||
}; | }; | ||
const char * | const char *s_CustomPrint = | ||
"import sys, emb\n" | "import sys, emb\n" | ||
"class CustomPrint():\n" | "class CustomPrint():\n" | ||
| Line 24: | Line 24: | ||
"\n" | "\n" | ||
" def write(self, text):\n" | " def write(self, text):\n" | ||
" | " self.old_stdout.write('CustomPrint called')\n" | ||
" text = text.rstrip()\n" | " text = text.rstrip()\n" | ||
" if len(text) == 0:\n" | " if len(text) == 0:\n" | ||
" return\n" | " return\n" | ||
" emb.print(self, text)" | " emb.print(self, text)" | ||
"\n"; | "\n"; | ||
| Line 42: | Line 41: | ||
flags.cf_flags = PyCF_SOURCE_IS_UTF8; | flags.cf_flags = PyCF_SOURCE_IS_UTF8; | ||
logObjectP = Py_CompileStringFlags( | logObjectP = Py_CompileStringFlags(s_CustomPrint, "CustomPrint", Py_single_input, &flags); | ||
ERR_NULL(logObjectP, tsmUnsupScriptLanguageErr); | ERR_NULL(logObjectP, tsmUnsupScriptLanguageErr); | ||
Revision as of 18:12, 24 July 2013
// CPython.cpp
#include "stdafx.h"
#include "CFUtils.h"
#include <Python/Python.h>
#include "CPython.h"
static PyObject* emb_print(PyObject *self, PyObject *args)
{
Log("emb_print called");
return self;
}
static PyMethodDef EmbMethods[] = {
{"print", emb_print, METH_VARARGS, "Calls custom print function."},
{NULL, NULL, 0, NULL}
};
const char *s_CustomPrint =
"import sys, emb\n"
"class CustomPrint():\n"
" def __init__(self):\n"
" self.old_stdout=sys.stdout\n"
"\n"
" def write(self, text):\n"
" self.old_stdout.write('CustomPrint called')\n"
" text = text.rstrip()\n"
" if len(text) == 0:\n"
" return\n"
" emb.print(self, text)"
"\n";
OSStatus CPython_PreAlloc(const char *utf8Z)
{
OSStatus err = noErr;
PyCompilerFlags flags;
PyObject *logObjectP = NULL;
Py_SetProgramName(const_cast<char *>(utf8Z));
Py_Initialize();
flags.cf_flags = PyCF_SOURCE_IS_UTF8;
logObjectP = Py_CompileStringFlags(s_CustomPrint, "CustomPrint", Py_single_input, &flags);
ERR_NULL(logObjectP, tsmUnsupScriptLanguageErr);
if (!err) {
ERR(PySys_SetObject("stdout", logObjectP));
ERR(PySys_SetObject("stderr", logObjectP));
Py_DECREF(logObjectP);
}
logObjectP = Py_InitModule("emb", EmbMethods);
ERR_NULL(logObjectP, tsmUnsupScriptLanguageErr);
return err;
}
void CPython_PostDispose()
{
Py_Finalize();
}
void CPython_Test()
{
PyRun_SimpleString(
"from time import time, ctime\n"
"print 'Today is', ctime(time())\n");
}