Redirect stdout to a buffer [Errno 9]

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Mon Nov 16 13:21:10 EST 2009


En Mon, 16 Nov 2009 14:17:52 -0300, Ecir Hana <ecir.hana at gmail.com>  
escribió:

>> I'm trying to write a simple Win32 app, which may run some Python
>> scripts. Since it is a Windows GUI app, I would like to redirect all
>> output (Python print, C printf, fprinf stderr, ...) to a text area
>> inside the app. In other words, I'm trying to log all the output from
>> the app (C, Python) to a window. So far, this works for C printf():
>> [...]
>> PS: Maybe I'm doind something wrong, but SetStdHandle() does not work
>> at all....

This worked for me:

#include <windows.h>
#include "Python.h"

int main()
{
   HANDLE hReadPipe, hWritePipe;
   DWORD nr, nw;
   char buffer[100];

   CreatePipe(
     &hReadPipe,
     &hWritePipe,
     NULL,
     1024);
   SetStdHandle(STD_OUTPUT_HANDLE, hWritePipe);

   Py_Initialize();
   PyRun_SimpleString("print 'from Python'");
   Py_Finalize();

   puts("from C\n");

   CloseHandle(hWritePipe);
   ReadFile(hReadPipe, buffer, 19, &nr, NULL);
   CloseHandle(hReadPipe);
   WriteFile(GetStdHandle(STD_ERROR_HANDLE), buffer, nr, &nw, NULL);
}

> Also, maybe this matters: it's on WinXP, Python 2.6 and MinGW GCC.

I'm using Visual Studio 2008 Express Edition.

-- 
Gabriel Genellina




More information about the Python-list mailing list