Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

redirecting stdio

97 views
Skip to first unread message

Keith S.

unread,
Jul 12, 2002, 11:56:27 AM7/12/02
to
Hi,

I'm rather new to Python and am trying to embed it into a C++
application. The documentation gives the basics of this, but
I want Python's output (stdio/stderr) to be redirected to C++
functions (to display the text in a message window).

Can anyone point me to a description or example of how this is
done?

thanks,

Keith

Alex Martelli

unread,
Jul 12, 2002, 1:17:39 PM7/12/02
to
Keith S. wrote:

Here's a little thing I had laying around -- not quite what
you ask, but it might help. It's a small demonstrative C
extension which does just about the bare minimum needed to
show how to redirect Python's stdout from C when imported.


#include <Python.h>
#include <stdio.h>

static PyObject*
redi(PyObject* self, PyObject* args)
{
char* thestring;
if(!PyArg_ParseTuple(args, "s", &thestring))
return 0;
printf("Print string: (%s)\n", thestring);
return Py_BuildValue("");
}

static PyMethodDef rediMethods[] = {
{"redi", redi, METH_VARARGS, "Redirect ouput"},
{0}
};

void
initredi(void)
{
PyObject* sys_module = PyImport_ImportModule("sys");
PyObject* redi_module = Py_InitModule("redi", rediMethods);
PyObject* redi_dict = PyModule_GetDict(redi_module);
PyObject* aux;
char * code = "class Sout:\n"
" def write(self, s): redi(s)\n"
"sout = Sout()\n";

aux = PyRun_String(code, Py_file_input, redi_dict, redi_dict);
Py_XDECREF(aux);
aux = PyObject_GetAttrString(redi_module, "sout");
PyObject_SetAttrString(sys_module, "stdout", aux);
Py_XDECREF(aux);
}


Alex

0 new messages