linopy
linopy copied to clipboard
More control over solver logs and printing to console
I would appreciate an easy way to not only set the log file for a solver to write into, but also to deactivate the stdout print during a solve process. This would remove the clutter when solving multiple small models.
On top of that, a way to kook into the text stream of the solving progress could be nice, but that's less important.
My temporary solution for this is using a context manager an wrapping the solve it:
import os
import sys
from contextlib import contextmanager
@contextmanager
def suppress_output():
"""Redirect both Python and C-level stdout/stderr to os.devnull."""
with open(os.devnull, 'w') as devnull:
# Save original file descriptors
old_stdout_fd = os.dup(1)
old_stderr_fd = os.dup(2)
try:
# Flush any pending text
sys.stdout.flush()
sys.stderr.flush()
# Redirect low-level fds to devnull
os.dup2(devnull.fileno(), 1)
os.dup2(devnull.fileno(), 2)
yield
finally:
# Restore fds
os.dup2(old_stdout_fd, 1)
os.dup2(old_stderr_fd, 2)
os.close(old_stdout_fd)
os.close(old_stderr_fd)
m = linopy.Model()
with suppress_output():
m.solve()
Regular contextlib.redirect_stdout and contextlib.redirect_stderrunfortunately don't work for all solvers (HiGHS and some other solvers like CBC write directly to the C/C++ level stdout, bypassing Python’s sys.stdout)