Embedding Python in Windows Applications

Mark Hammond MarkH at ActiveState.com
Sat Dec 30 19:25:09 EST 2000


Gerson Kurz wrote:

> If I embedd Python in a Win32 console application (using
> Demo\embed.c), everything works fine. If I take the very same piece of
> code and put it in a Win32 Windows application (not MFC, just a plain
> WinMain()) I see no output (and more importantly so, no errors),
> because the application does not have a stdout/stderr set up. 
> 
> I have made the following "hack" to make it work (in VisualStudio)
> 
>     // stdout, stderr as defined in the MSVCRT
>     _iob[1] = *fopen("D:\\stdout.log","w");
>     _iob[2] = _iob[1];
> 
> but that surely cannot be a longterm solution. I don't want the output
> to be written to a temp file, I want to see it in a callback. Is that
> possible, and if so, how ? 

There is not much Python can do here, but it does provide tools to help you.

When Python initialized, "sys.stdout" and "sys.stderr" will be set to 
the C runtime stdout and stderr handles.

As you discovered, a GUI app doesnt have a valid stderr or stdout. 
Therefore, you may choose to set a valid C runtime stderr and stdout as 
your app initializes.  However, only you know what makes sense for you app.

Python itself always prints via "sys.stdout" and "sys.stderr".  Thus, if 
the first thing you do is to set sys.stdout and sys.stderr to some 
object of yours, again you have full control over where this output 
goes.  But again, only you know what makes sense.


IMO, you best solution is for your app to:
* Execute some Python "bootstrap" code.  This code should set sys.stderr 
etc to something useful.  If necessary, this Python implemented code 
could still callback into your application via your existing extension 
mechanisms.

* Once this bootstrap code has executed, you can then run your "normal" 
code in the knowledge that all errors etc will go somewhere useful (ie, 
to the object created in the bootstrap phase).

You probably would have special handling for the bootstrap phase - eg, 
maybe you _could_ still temporarily set stderr to "%TEMP%\stderr.log". 
If the bootstrap code fails, this log will tell you why.  If it 
succeeds, you could delete the log file, safe in the knowledge that 
subsequent errors will end up to your new sys.stdout/stderr objects.

Mark.




More information about the Python-list mailing list