By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,885 Members | 1,499 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,885 IT Pros & Developers. It's quick & easy.

Redirect output

P: n/a
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:

Expand|Select|Wrap|Line Numbers
  1. import MyCProg, sys
  2.  
  3. f = open("tmp.txt", "wb")
  4. sys.stdout = f
  5. MyCProg.getData()
  6. f.close()
  7. sys.stdout = sys.__stdout__
  8.  
  9. print open("tmp.txt", "rb").read()
  10.  
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.

Mar 28 '06 #1
Share this Question
Share on Google+
1 Reply


P: n/a
In article <11**********************@u72g2000cwu.googlegroups .com>,
"abcd" <co*******@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:

Expand|Select|Wrap|Line Numbers
  1.  import MyCProg, sys
  2.  f = open("tmp.txt", "wb")
  3.  sys.stdout = f
  4.  MyCProg.getData()
  5.  f.close()
  6.  sys.stdout = sys.__stdout__
  7.  print open("tmp.txt", "rb").read()
  8.  

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, do**@u.washington.edu
Mar 28 '06 #2

This discussion thread is closed

Replies have been disabled for this discussion.