Redirect output

A

abcd

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()

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.
 
D

Donn Cave

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()

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, (e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top