Mailing List Archive

Redirecting Python Output
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?

Thanks,

Alberto
alberto@totallygames.com
Redirecting Python Output [ In reply to ]
Alberto Fonseca <alberto@totallygames.com> 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
try:
from cStringIO import StringIO
except:
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));
Py_DECREF(str);
Py_DECREF(sys_stdout);

-Arcege