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.