1

I'm using a SWIG module in a Python script and I would like to redirect/mute excess output printed on the screen by the module. I'm aware of the possibility to redirect stdout/stderr within the Python script, eg. using redirect_stdout from the contextlib. Problem is, however, that the C++ program wrapped by SWIG defines its own IO stream which apparently is not being caught by the stdout definitions in my Python script.

The module is part of a library: https://github.com/federicomarulli/CosmoBolognaLib

I think the relevant stream definition is in file Headers/Kernel.h starting from line 675:

inline std::ostream &headerCBL (std::ostream &stream)
{
stream << par::col_blue << "CBL > " << par::col_default;
   return stream;
}

#define coutCBL std::cout << headerCBL

This is used for example by the function wp_DM defined in Cosmology/Lib/Cosmology.cpp eg. line 949:

coutCBL <<"I'm writing the file: "<<file_table<<endl;

Here is my test Python script:

import CosmoBolognaLib as cbl
from contextlib import redirect_stdout, redirect_stderr
import os, sys

cosmo = cbl.Cosmology(cbl.CosmologicalModel__Planck15_)
cosmo.set_sigma8(0.8)
with open(os.devnull, 'w') as out, redirect_stdout(out):
    cosmo.wp_DM(1., 'EisensteinHu', 0., 50., False)

I would expect there to be no output but instead all the printout is there. I have also tried redirecting stderr to devnull with sam results. Modifying the underlying C++ program would be difficult so doing this at the Python level would be highly preferable. I'm using Linux.

ovlindho
  • 33
  • 4
  • Do you have the source code for the he module that's too chatty? Are you on windows or Linux? – Flexo Oct 14 '19 at 15:39
  • @Flexo I added some information about the C++ code. And I'm running on Linux. – ovlindho Oct 15 '19 at 09:55
  • This answer with the `rdbuf()` calls inside`%exception` should work for you I think: https://stackoverflow.com/a/37635295/168175 if you're able to modify the SWIG interface for the library you're using. – Flexo Oct 15 '19 at 17:15
  • There would be options using Python/ctypes and `dup2` I think, but I'd suggest modifying the SWIG interface is much cleaner and simpler unless you don't have a choice – Flexo Oct 15 '19 at 17:17

0 Answers0