Redirect output

Donn Cave donn at u.washington.edu
Tue Mar 28 15:27:12 EST 2006


In article <1143571506.345460.298260 at u72g2000cwu.googlegroups.com>,
 "abcd" <codecraig at gmail.com> wrote:
> I have a program which is written in C and interfaced with python via
> Swig.  However, the function I call prints stuff out to the console.  I
> would like to capture what it is printing out.  I tried:
> 
> [code]
> import MyCProg, sys
> 
> f = open("tmp.txt", "wb")
> sys.stdout = f
> MyCProg.getData()
> f.close()
> sys.stdout = sys.__stdout__
> 
> print open("tmp.txt", "rb").read()
> [/code]
> 
> However, it just prints the data to the screen.  I tried redirecting
> stderr as well.
> 
> other than modifying the C code and re-generating the interface via
> Swig, any ideas?  just asking before i have to do that.

As you probably surmised, C I/O doesn't notice when you've
swapped the stdout object in the Python sys module.

If that's what you're trying to do, redirect the output of
something like printf() or puts(), then you might look at
the os.dup2() function as a way to redirect unit 1.  Get
the new output unit from os.open() with os.O_CREAT plus whatever
other flags, or open the output file some other way that
creates a file object and use its fileno() function.  Flush
stdout before each dup2().

To revert back to the original stdout, you will want a
copy of that stream, which you can get with the os.dup()
function, prior to redirection.  All the left over file
descriptors can be closed afterwards.

I assume you're on a UNIX platform or something to that effect.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list