Redirecting Python Output

Michael P. Reilly arcege at
Mon Aug 16 20:44:33 EDT 1999

Alberto Fonseca <alberto at> wrote:
: Hello, I am embedding Python into my app under Windows.  I would like to
: redirect Python's output so that I can just print it myself.  Has anyone
: done this?  What is the easiest way to do this?

Probably something like:

    import sys
      from cStringIO import StringIO
      from StringIO import StringIO
    sys.stdout = StringIO()
    sys.stderr = StringIO()

Each file output is seperate here, but could be the same to redirect
the output to both places.  This will allow you to retrieve it in your
embedded C program thusly:

    PyObject *sys_stdout, *str;
    sys_stdout = PySys_GetObject("stdout");
    str = PyObject_CallMethod(sys_stdout, "getvalue", NULL);
    fprintf(stderr, "Python output: %s\n", PyString_AsString(str));


More information about the Python-list mailing list