让python 程序清爽一些

背景

在使用一些第三方python 库时,偶尔会出现一些不需要的信息打印到终端。更改第三方代码能暂时解决问题,但是在第三方库更新之后可能又会出现。

方法

利用with方法将在with作用域内的所有函数的stdout都指向到devnull, 离开with作用域后将stdout恢复。
定义如下类:

class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout.close()
        sys.stdout = self._original_stdout

定义一个测试方法:

class StaticCls():
    call_cnt = 0
    def test_print(self):
        StaticCls.call_cnt += 1
        print("This function has been called %s times" % StaticCls.call_cnt)

with HiddenPrints():
    cls = StaticCls()
    cls.test_print()

cls = StaticCls()
cls.test_print()

运行结果如下:
pic可见虽然test_print() 被执行两次,但是我们在终端只看到第二次调用的输出。