0

I am attempting to capture output of an error, whose output is produced by PrErr_Print()

However, no output is appearing. Here is what I have tried, via this thread:

Redirect Embedded Python IO to a console created with AllocConsole

PyObject* sys = PyImport_ImportModule("sys");
PyObject* io = PyImport_ImportModule("io");
PyObject* pystdout = PyObject_CallMethod(io, "open", "ss", "CONOUT$", "wt");
PyObject_SetAttrString(sys, "stderr", pystdout);
if (PyErr_Occurred()) {
    printf("Could not redirect python stderr to stdout\n");
    PyErr_Print();
    extensions_destroy();
    return 0;
}

And the creation of the console

/**
 * Enable debug console
 */
void debug_enable( void ) {
    AllocConsole();
    freopen("CONOUT$", "w", stdout);
    freopen("CONOUT$", "w", stderr);
    printf("Debug mode enabled.\n");
}

I have also attempted to redirect python stderr to it's stdout to no avail.

Community
  • 1
  • 1
rscarson
  • 262
  • 3
  • 13
  • Python 2.7, And yes, the call is shown in the second block of code... Not python stderr and stdout work perfectly – rscarson Feb 22 '16 at 01:03
  • Ah I see, sorry... Yeah debug_enable is called well before python is initialized – rscarson Feb 22 '16 at 01:06
  • The debug console works perfectly. It's only the output of PyErr_Print that is not visible. If I compile with a console, it works – rscarson Feb 22 '16 at 01:10
  • `io.open` in text mode requires `unicode` strings, but `PyFile_WriteString` writes regular `str` byte strings. You can use unbuffered binary mode `PyObject_CallMethod(io, "open", "ssi", "CONOUT$", "wb", 0);`. Or just use a regular 2.x `file` like in the linked answer. – Eryk Sun Feb 22 '16 at 02:05
  • That worked, thank you – rscarson Feb 22 '16 at 02:08
  • I think it's simpler to use `PyObject* pystdout = PyFile_FromString("CONOUT$", "w"); PyFile_SetBufSize(pystdout, 0);` instead of using `io.open`. I wish there were a simple way to execute the `freopen` function of Python's CRT. Then you wouldn't need any of this. You could just fix up Python's C `stderr` before calling `Py_Initialize`. – Eryk Sun Feb 22 '16 at 02:40

0 Answers0