在使用python调用函数时,想将函数中的print输出禁止掉又不想改函数的代码,可以定义如下HiddenPrints类解决:
class HiddenPrints:
def __enter__(self):
self._original_stdout = sys.stdout
sys.stdout = open("", 'w')
def __exit__(self, exc_type, exc_val, exc_tb):
sys.stdout.close()
sys.stdout = self._original_stdout
我们只需要将想要隐藏打印的函数,在with HiddenPrint(): 作用域下使用即可:
with HiddenPrints():
function()