linopy icon indicating copy to clipboard operation
linopy copied to clipboard

More control over solver logs and printing to console

Open FBumann opened this issue 3 months ago • 1 comments

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.

FBumann avatar Sep 24 '25 20:09 FBumann

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)

FBumann avatar Oct 15 '25 00:10 FBumann