how: embed + extend to control my running app?

David M. Cotter me at davecotter.com
Wed Jul 24 18:10:28 CEST 2013


well, umm, gosh, now i feel quite silly.  that was easy.  okay that's done.

next: i'd like to redirect the output of any "print" statements to my C function:

>	void	Log(const unsigned char *utf8_cstrP);

on the mac, python output sys.stdout goes into the debug console if you're in the debugger, and to the "console app" if not.  On windows, i don't think it goes anywhere at all?

So: i really want it to go to my own log file (via my Log() function).  now, can i specify "please output to this FILE*" ?, i looked at all the python c headers but found nothing about redirecting the output.

I see "PySys_GetFile()" which will get what it points to, but what i want is a "PySys_SetFile()" so i can set it.

the only alternative seems to be:
>	PyObject	*logObjectP = create ???;
>	
>	ERR(PySys_SetObject("stdout", logObjectP));

if that's the only way, how to create the logObjectP such that it redirects the write() python function to my Log() C function?

i tried this:
--------------------------------
const char *s_printFunc = 
	"import sys\n"
	"class CustomPrint():\n"
	"	def __init__(self):\n"
	"		self.old_stdout=sys.stdout\n"
	"\n"
	"	def write(self, text):\n"
	"		self.old_stdout.write('foobar')\n"
	"		text = text.rstrip()\n"
	"		if len(text) == 0:\n"
	"			return\n"
	"		self.old_stdout.write('custom Print--->' + 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_printFunc, "CustomPrint", Py_single_input, &flags);

	ERR_NULL(logObjectP, tsmUnsupScriptLanguageErr);
	
	if (!err) {
		ERR(PySys_SetObject("stdout", logObjectP));
		ERR(PySys_SetObject("stderr", logObjectP));
		Py_DECREF(logObjectP);
	}
	
	return err;
}

void	CPython_PostDispose()
{
	Py_Finalize();
}

void	CPython_Test()
{
	PyRun_SimpleString(
		"from time import time, ctime\n"
		"print 'Today is', ctime(time())\n");
}

-----------------------------------------
and when i run CPython_Test(), there is no output at all.  If i comment out the entire Py_CompileStringFlags() line, then the output works fine (going to stdout as expected), so i'm not sure what i'm doing wrong



More information about the Python-list mailing list