gpt4 book ai didi

Python-撤消标准输出重定向

转载 作者:行者123 更新时间:2023-11-28 20:44:49 25 4
gpt4 key购买 nike

所以我知道

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com