1

I'm trying to redirect the output of the constructor of an object that is created by a shared library to /dev/null. The side effect of the construction is the printing of lots of junk that I don't need. The code is as follows:

f = open("/dev/null", 'w')
tmpErr = sys.stderr
tmpOut = sys.stdout
sys.stderr = f
sys.stdout = f
foo = Foo(param1, param2)
sys.stderr = tmpErr
sys.stdout = tmpOut
f.close()

If I replace the function call with a simple print (print "hello", for example) or a call to a local function, the redirection seems to work. Also, using the ">&" operator in the shell (tcsh) I managed to redirect all the output perfectly.

What am I missing here?

White Zebra
  • 179
  • 1
  • 3
  • 15
  • What does `(call a library function)` look like? – Blender Feb 03 '13 at 10:57
  • @Blender I edited the question – White Zebra Feb 03 '13 at 11:04
  • 2
    @WhiteZebra, what does Foo do? A common problem is when you reference a DLL, or other program, it uses native functions like `printf`. They don't respect Python's `sys` module, because they don't know it exists. Depending on what Foo does, and how you're interacting with the shared library infulences how you solve the problem. – Brigand Feb 03 '13 at 11:09
  • 1
    related: [How do I prevent a C shared library to print on stdout in python?](http://stackoverflow.com/q/5081657/4279) – jfs Feb 03 '13 at 11:19
  • @FakeRainBrigand I don't know what the library does exactly. It's a black box for me. I only know that it's written in C++. – White Zebra Feb 03 '13 at 11:55
  • @J.F.Sebastian It seems promising! Will check this out... – White Zebra Feb 03 '13 at 11:56
  • @J.F.Sebastian Solved it with your link! I also used [this link](http://stackoverflow.com/questions/8804893/redirect-stdout-from-python-for-c-calls) which made me realize that I need to have another redirect function for stderr. – White Zebra Feb 03 '13 at 12:19
  • for stderr use `2` everywhere instead of `1` for stdout – jfs Feb 03 '13 at 12:28

0 Answers0