471,343 Members | 1,391 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,343 software developers and data experts.

Redirecting STDOUT using C calls.

I'm trying to redirect python's stdout to another location. The
reason for this is that I'm embedding python in an application. Now,
originally my code was developed for Linux and that did not require
redirection due to the fact that every X11 application can have an
STDOUT associated with it. I then proceeded to take interest in making
my code portable and looked at compiling it on windows, however Win32
GUI applications are not given an STDOUT by default. One has to first
AllocConsole() and then reassign the handles using magic tokens
"CON(IN|OUT)$" such as freopen("CONOUT$", "w", stdout). I like to keep
code clean and would like to stick to the C API as much as possible.
I dived into the source and figured out two ways of doing it:

#include <Python.h>
#include <iostream>

// Demonstrates redirection after initialisation.
int main() {
FILE* afile = fopen("zig.txt", "w+");
PySys_SetObject("stdout", PyFile_FromFile(afile, "zig.txt",
"wb", fclose));
// I would be using boost::python::exec, but let's stick to basics.
return 0;
#include <Python.h>
#include <cstdio>
#include <iostream>

// Demonstrates redirection before initialisation.
int main() {
FILE* afile = fopen("zig.txt", "w+");
// All of this program's output to file.
stdout = afile;
return 0;

For exemplary purposes, i've used files as the target for
redirection, however the actual target in windows would be the FILE*
gained from opening the "CONOUT$" virtual file. Both of these examples
compile and work fine on linux, however I get an illegal access
exception (a SIGSEGV equivalent i think) on Windows (XP). Why? The
illegal access happens on the line that executed the python print()
function. What is the cause for this and how can i fix it?
It may also help to mention that the following *Python* code works
in Windows:
import sys
sys.stdout = open("CONOUT$", "w", 0)
So if this works, there must be a difference between how the inbuilt
open() opens and assigns the pointers than how the C API does it. Any ideas?

Thank you.
Dec 30 '07 #1
0 1675

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Michael McGarry | last post: by
3 posts views Thread by Laszlo Zsolt Nagy | last post: by
15 posts views Thread by Matt Burland | last post: by
9 posts views Thread by Fuzzyman | last post: by
8 posts views Thread by Morpheus | last post: by
6 posts views Thread by drhilbert | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.