I want to suppress the console output from an f2py extension module. Standard approaches like the following don't work, because the Fortran output comes from another place than standard Python print commands (?) So the Fortran output will still be printed to the console.
from contextlib import redirect_stdout
import io
with redirect_stdout(io.StringIO()) as f:
call_my_f2py_module()
Until recently I have been working with this, and it worked:
class LoggerLowLevelMuted():
"""A logger to mute low level output form Fortran modules
Inspired from https://stackoverflow.com/a/17753573/8028981"""
def __init__(self, filename=None):
self.filename = filename
if filename is None:
self.filename = os.devnull
self.stdchannel = sys.__stdout__
def __enter__(self):
self.dest_file = open(self.filename, 'a')
self.oldstdchannel = os.dup(self.stdchannel.fileno())
os.dup2(self.dest_file.fileno(), self.stdchannel.fileno())
os.close(self.stdchannel.fileno())
def __exit__(self, exc_type, exc_val, exc_tb):
os.dup2(self.oldstdchannel, self.stdchannel.fileno())
self.dest_file.close()
os.close(self.oldstdchannel)
and then:
with log.LoggerLowLevelMuted(filename=nfmds_logfile):
call_my_f2py_module()
I want to be honest, I have no clue what that class exactly did, but it worked in the sense that the Fortran output from the f2py module was suppressed. It still works under Linux, but under Windows I now get the following error (only since recently):
OSError: [WinError 6] Invalid handle
To reproduce the error, you can run (under Windows):
with LoggerLowLevelMuted(filename="testout.txt"):
print("test")
Can anybody see what is going wrong and what I can do to fix the problem?
The topic is related to this question.
Edit: Another related post is this one.