基于@fakerainbrigan解决方案,我建议一个更安全的解决方案:import os, sys
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
然后你可以这样使用它:with HiddenPrints():
print("This will not be printed")
print("This will be printed as before")
这更安全,因为您不能忘记重新启用stdout,这在处理异常时尤其重要。# This is an example of not-so-good solution
# without 'with' context manager statement.
try:
disable_prints()
something_throwing()
# enable_prints() This wouldn't be enough!
except ValueError:
handle_error()
finally:
enable_prints() # That's where it needs to go.
如果您忘记了finally子句,那么您的print调用将不再打印任何内容。使用with语句,这是不可能的。
使用sys.stdout = None是不安全的,因为有人可以调用sys.stdout.write()等方法