| Store | Cart

redirecting stdio

From: Alex Martelli <ale...@aleax.it>
Fri, 12 Jul 2002 17:17:39 GMT
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

Recent Messages in this Thread
Keith S. Jul 12, 2002 03:56 pm
Alex Martelli Jul 12, 2002 05:17 pm
Messages in this thread