coin-or / python-mip

Python-MIP: collection of Python tools for the modeling and solution of Mixed-Integer Linear programs
Eclipse Public License 2.0
518 stars 92 forks source link

documentation: avoiding CBC stdout on console #176

Closed pabloazurduy closed 3 years ago

pabloazurduy commented 3 years ago

In case you are looking into a way to eliminate the CBC output on your console you can try with the following context manager

@contextlib.contextmanager
def ignore_output():
    import os 
    with open('model_stdout.log', 'w') as f:
        orig_std_out = os.dup(1)
        os.dup2(f.fileno(), 1)
        yield # pause the coroutine to execute the context code
        os.dup2(orig_std_out, 1)
        os.close(orig_std_out)

#usage
with ignore_output() as iocm:
    # > this output will be redirected to the 'model_stdout.log' file 
    some_model.optimize(max_seconds=500)