Skip to content Skip to sidebar Skip to footer

Redirect Embedded Python Io To A Console Created With Allocconsole

I am having some trouble getting Python IO redirected to a console that I've allocated for my Win32 app. Is there a Python-specific stream that I need to redirect? Here's more-or-l

Solution 1:

Set sys.stdout on the Python side (presumably to an open('CONOUT$', 'wt')) to make Python's print work, and similarly for sys.stderr and sys.stdin. (There are faster ways to make this happen from a C extension, but the simplest way is to just execute the Python statements, with a import sys in front;-).

Why: because Python's runtime, on startup, found the standard FDs closed, set sys.stdout and friends accordingly, and is not going to check again and set them differently -- so you just set them yourself, explicitly, and it will be fine.

If you're keen to do it all at C-API level, it will take a few lines, but of course it can be done...

PyObject* sys = PyImport_ImportModule("sys");
PyObject* pystdout = PyFile_FromString("CONOUT$", "wt");
if (-1 == PyObject_SetAttrString(sys, "stdout", pystdout)) {
  /* raise errors and wail very loud */
}
Py_DECREF(sys);
Py_DECREF(pystdout);

this is the exact equivalent of the single Python line:

sys.stdout = open('CONOUT$', 'wt')

Solution 2:

It is much easier to just tell the embedded python to redirect its output to a file.

Try this code:

PyRun_SimpleString("import sys\n");
PyRun_SimpleString( "sys.stdout = sys.stderr = open(\"C:\\embedded_log_file.txt\", \"w\")\n" );

Post a Comment for "Redirect Embedded Python Io To A Console Created With Allocconsole"