Using JF Sebastian stdout_redirected , you can redirect stdout at the file descriptor level to os.devnull.
with stdout_redirected(): soln2 = integrate.odeint(f, y2, t2, mxstep = 5000)
Outside of with-statement
, stdout is still printing. Inside with-suite
stdout is suppressed.
For example, here is an example of Caeiro odeint , whose lsoda warnings are suppressed by stdout_redirected
.
import os import sys import contextlib import numpy as np import scipy.integrate as integrate from numpy import pi def fileno(file_or_fd): fd = getattr(file_or_fd, 'fileno', lambda: file_or_fd)() if not isinstance(fd, int): raise ValueError("Expected a file (`.fileno()`) or a file descriptor") return fd @contextlib.contextmanager def stdout_redirected(to=os.devnull, stdout=None): """ /questions/7962/redirect-stdout-to-a-file-in-python/57093#57093 (JF Sebastian) """ if stdout is None: stdout = sys.stdout stdout_fd = fileno(stdout)
The warnings that lsoda writes to stdout are suppressed.
source share