我试图用一个with
声明来压制sys.stdout
或sys.stderr
单独。 我找到了一个不起作用的教程。我正在使用Python 3.6.4
,我认为本教程是Python 2
.
我在 SO 上查找了它,发现了一些但应用程序不起作用或不适用于这种情况。
这不适用:Python subprocess supress stdout 和 stderr
无法使任何with
语句起作用:
从 Python 函数中抑制 stdout / stderr 打印
这适用于 fortran:在 Python 中重定向 FORTRAN(通过 F2PY 调用)输出
from contextlib import contextmanager
@contextmanager
def suppress_console(file=sys.stdout):
with open(os.devnull, "w") as devnull:
old_file = file
file = devnull
try:
yield
finally:
file = old_file
with suppress_console():
print(1, file=sys.stdout)
# 1