在Spyder for Python中,将控制台打印到日志文件是不可逆的

2024-06-28 19:50:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用Spyder for Python,有时我想将控制台打印到日志文件中(在输出很长的情况下),有时我只想在控制台上输出。为此,我在Python文件中使用以下构造:

在文件的开头:

import sys
# specify if the output should be printed on a separate log file or on the console
printLogToFile = False

if printLogToFile == True:
    #Specify output file for the logs
   sys.stdout = open('C:/Users/User 1/logfile.txt', 'w')

在文件末尾:

# Close the log file if output is printed on a log file and not on the console
if printLogToFile == True:
    sys.stdout.close()
    sys.stdout = sys.__stdout__

基本上,每当我的布尔变量printLogToFile的值为False时,所有内容都会在控制台上按应有的方式打印出来,每当它的值为True时,所有内容都会打印到日志文件中。但是,一旦我用printLogToFile=True运行了一次文件,就不能再恢复了。即使变量的值为False,它仍然会将所有内容打印到日志文件中,而不是控制台上。更奇怪的是,对于其他与该文件没有任何连接的Python文件,控制台也不再打印到控制台上。解决此问题的唯一方法是关闭Spyder并重新启动它

你知道为什么会发生这种情况以及如何避免这种情况吗?我很感激你的每一句话


Tags: 文件thelogfalsetrue内容outputif
1条回答
网友
1楼 · 发布于 2024-06-28 19:50:28

Spyder中的控制台是一个IPython控制台,而不是一个普通的Python控制台,因此我认为IPython正在对stdout进行一些操作,这会导致您的方法失败

这个{a2}{}说

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.

换句话说,尝试:

if printLogToFile:
    prev_stdout = sys.stdout
    sys.stdout = open('C:/Users/User 1/logfile.txt', 'w')

# code that generates the output goes here

if printLogToFile:
    sys.stdout.close()
    sys.stdout = prev_stdout

作为替代方案,基于this answerthis answer假设Python>;=3.7中,您可以使用contextlibwith语句有选择地捕获某些代码的输出。这在Spyder 4和5中似乎对我有效:

from contextlib import redirect_stdout, nullcontext

if printLogToFile:
    f = open('myfile.txt', 'w')
    cm = redirect_stdout(f)
else:
    cm = nullcontext()

with cm:
    # code that generates the output goes here

如果您想执行整个Python脚本myscript.py并捕获它输出的所有内容,那么不修改脚本并从包装器脚本调用它可能更容易:

# put this in the same folder as myscript.py

from contextlib import redirect_stdout

with redirect_stdout(open('myfile.txt', 'w')):
    import myscript
 

如果您想要比这更灵活的东西,可能是开始使用logging的时候了

相关问题 更多 >