Python-撤消标准输出重定向

标签 python

所以我知道

Redirecting stdout to "nothing" in python

您可以抑制打印语句。但是是否有可能稍后撤消该命令,以便在特定点之后,打印语句确实会再次打印?

例如,假设我想打印“b”而不是“a”。

我会这样做:

import os
f = open(os.devnull, 'w')
sys.stdout = f

print("a")

# SOME COMMAND

print("b")

有人能告诉我什么是“某些命令”吗?

最佳答案

原始sys.stdout总是保存在sys.__stdout__中:

sys.stdout = sys.__stdout__

但是,文档确实指出,首选显式保存原始 sys.stdout:

It can also be used to restore the actual files to known working file objects in case they have been overwritten with a broken object. However, the preferred way to do this is to explicitly save the previous stream before replacing it, and restore the saved object.

关于Python-撤消标准输出重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25336087/

相关文章:

python - 在 Django 模型类上设置 __new__ 是否安全?

python - 我可以在 Tkinter 应用程序上获取 Youtube 缩略图吗

python - 如何从 Pandas 数据框中的每一列创建子图

python - Python中global关键字的使用

VideoWriter.write 中的 Python OpenCV 错误 (-215)

python - 比较两个列表并返回不匹配的项目

python - 如何从django中的模型中获取一个字段

Python 计算字典中值的出现次数

Python REPL : issuing commands in advance to execute after block

python - types.MethodType 是如何使用的?