Suppressing Stan optimizer printing in Python
1 # from https://stackoverflow.com/questions/11130156/suppress-stdout-stderr-print-from-python-functions 2 class suppress_stdout_stderr(object): 3 ''' 4 A context manager for doing a "deep suppression" of stdout and stderr in 5 Python, i.e. will suppress all print, even if the print originates in a 6 compiled C/Fortran sub-function. 7 This will not suppress raised exceptions, since exceptions are printed 8 to stderr just before a script exits, and after the context manager has 9 exited (at least, I think that is why it lets exceptions through). 10 11 ''' 12 def __init__(self): 13 # Open a pair of null files 14 self.null_fds = [os.open(os.devnull, os.O_RDWR) for x in range(2)] 15 # Save the actual stdout (1) and stderr (2) file descriptors. 16 self.save_fds = (os.dup(1), os.dup(2)) 17 18 def __enter__(self): 19 # Assign the null pointers to stdout and stderr. 20 os.dup2(self.null_fds[0], 1) 21 os.dup2(self.null_fds[1], 2) 22 23 def __exit__(self, *_): 24 # Re-assign the real stdout/stderr back to (1) and (2) 25 os.dup2(self.save_fds[0], 1) 26 os.dup2(self.save_fds[1], 2) 27 # Close the null files 28 os.close(self.null_fds[0]) 29 os.close(self.null_fds[1])
使用:
1 # used like 2 with suppress_stdout_stderr(): 3 p = Propet(*kwargs).fit(training_data)