为什么sys.stdout(在python中)没有默认方法来恢复到默认值



在下面的编程中,首先我们将所有打印重定向到日志文件,然后关闭文件对象,然后再次将打印命令重新启动到交互式提示。

import sys
temp = sys.stdout                 # store original stdout object for later
sys.stdout = open('log.txt', 'w') # redirect all prints to this log file
print("testing123")               # nothing appears at interactive prompt
print("another line")             # again nothing appears. it's written to log file instead
sys.stdout.close()                # ordinary file object
sys.stdout = temp                 # restore print commands to interactive prompt
print("back to normal")           # this shows up in the interactive prompt

为什么python不支持这样的方法,将命令恢复到交互式模式

sys.stdout.default()

它几乎存在:sys.stdout = sys.__stdout__在程序开始时将stdout重置为其原始值

简单地说,但可能不会做你想做的事。您可以堆栈sys.stdout重定向,在这种情况下,恢复到以前的重定向而不是原来的重定向是有意义的。它在IDLE交互式解释器中的真实用例。最初的stdout在Windows上将为None,因为它是一个GUI程序,并且将被引导到您在Linux上启动它的终端。在重定向后的任何一种情况下,您肯定不想使用默认原始值,而是使用IDLE设置的值。

这就是为什么在重定向时应始终保存原始标准输出,并在不再需要重定向时恢复它的原因。

最新更新