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/

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

  • 相关阅读:
    mysql 常用的几个网址
    mysql 5.7 master/salve 切换
    oracle ebs 12.1.3 的一些日志路径
    postgresql 10.x 的命令 pg_test_fsync
    yii使用bootstrap分页样式
    Mysql让主键归0
    PHP基础知识练习
    ini_set的用法介绍
    php set_time_limit(0) 设置程序执行时间的函数
    php func_get_args
  • 原文地址:https://www.cnblogs.com/standby/p/14375401.html
Copyright © 2011-2022 走看看