如何记录脚本的输出

问题描述 投票:0回答:2

我想将 python 文件的输出记录到 txt 中。我也想在终端上看到它。

我尝试使用 sys.stdout,但它仍然没有终端输出。要记录它,我使用

f = open("log.txt", "r+")
打开日志文件,然后使用
set sys.stdout = f
。当代码结束时,
I said f.close()
写入更改。这是一些代码:

import sys
f = open("files/log.txt", "r+")
sys.stdout = f
print("You will not see this in terminal")
f.close()
python logging
2个回答
0
投票

记录模块

正如

CodeMaven42
提到的,您可以使用日志记录模块: 这是一个示例:

import logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.StreamHandler())
logging.basicConfig(filename='example.log', encoding='utf-8', level=logging.DEBUG)
logger.debug('This message should go to the log file')

这会将

This message should go to the log file
打印到控制台,并将
DEBUG:__main__:This message should go to the log file
放入
example.log

带T恤

您还可以使用

tee
linux 命令,该命令获取通过管道输入的内容,然后打印它并将其放入文件中:

print("Hello world!")
$ python my_script.py | tee somefile.log
Hello world!
$ cat somefile.log
Hello world!
    

0
投票
您可以使用

sys.stdout

 方法将 
write
 设置为类似文件的对象,该方法既写入原始 
sys.stdout
 又写入给定文件:

导入系统

T恤类: def

init(自身,文件): self.file = 文件 self.orig_stdout = sys.stdout

def write(self, text): self.orig_stdout.write(text) self.file.write(text) def __enter__(self): sys.stdout = self def __exit__(self, exc_type, exc_val, exc_tb): sys.stdout = self.orig_stdout
这样:

with open('test.txt', 'w') as file, Tee(file): print('both terminal and file') print('terminal only')
将输出到终端:

both terminal and file terminal only
并输出到文件:

both terminal and file
    
© www.soinside.com 2019 - 2024. All rights reserved.