zoukankan      html  css  js  c++  java
  • 关闭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/

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

  • 相关阅读:
    P3391 文艺平衡树
    隔离村庄(树形dp[01背包])
    cmd指令集
    vs的使用
    博客园第一天
    蓝桥杯 小生物的逃逸 模拟
    蓝桥杯 自行车停放 双向链表
    c++字符数组函数总结
    蓝桥杯 石子游戏 贪心
    蓝桥杯 最大获利 模拟
  • 原文地址:https://www.cnblogs.com/standby/p/14375401.html
Copyright © 2011-2022 走看看