redirecting stdio

Alex Martelli aleax at aleax.it
Fri Jul 12 13:17:39 EDT 2002


Keith S. wrote:

> 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?

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




More information about the Python-list mailing list