Redirect stdout to a buffer [Errno 9]

Ecir Hana ecir.hana at gmail.com
Mon Nov 16 16:04:21 EST 2009


On Nov 16, 7:21 pm, "Gabriel Genellina" <gagsl-... at yahoo.com.ar>
wrote:
> En Mon, 16 Nov 2009 14:17:52 -0300, Ecir Hana <ecir.h... 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

Hi,

thanks for the reply!

However, please, could you tell me how many bytes it read here:

ReadFile(hReadPipe, buffer, 19, &nr, NULL);

because for me, it has read 0. When I run your code, it prints from
both C and Python, but it prints straight to the console, not to the
buffer. Could you also please try to add:

WriteFile(GetStdHandle(STD_ERROR_HANDLE), "----\n", 5, &nw, NULL);

before:

WriteFile(GetStdHandle(STD_ERROR_HANDLE), buffer, nr, &nw, NULL);

Does it print "----" before "from Python" and "from C" for you?
Because for me it comes afterwards (as nr is 0)...



More information about the Python-list mailing list