关闭Python函数执行期间的标准输出

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)
作者:Standby一生热爱名山大川、草原沙漠,还有妹子
出处:http://www.cnblogs.com/standby/

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

原文地址:https://www.cnblogs.com/standby/p/14375401.html