Python: Difference between revisions

From kJams Wiki
Jump to navigation Jump to search
No edit summary
No edit summary
Line 17: Line 17:
};
};


// old name was "s_printFunc"
static const char *s_CustomPrint =  
static const char *s_CustomPrint =  
"import sys, emb\n"
"import sys, emb\n"

Revision as of 18:27, 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}
};

//	old name was "s_printFunc"
static 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"
	"\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");
}