简体   繁体   English

使用sys.stdout保存输出,但我想在控制台/终端上显示它

[英]saving output with sys.stdout, but I want to show it on console/terminal

So for analysis, I want to save everything the scripts outputs on the console/terminal, and for that I used sys.stdout : 因此,对于分析,我想保存脚本在控制台/终端上输出的所有内容,为此我使用了sys.stdout

My code: 我的代码:

sys.stdout = open('logFile.dat', 'w')
# TOO MUCH LINES OF CODE
sys.stdout.close()

My program is quite large, and there isn't point to copy-paste it here, because It doesn't affect my question. 我的程序非常大,没有必要在这里复制粘贴它,因为它不会影响我的问题。

So with this I get what I wanted but on the other hand, the console is blank while the program is running and that is a problem for me, because I want for program to output stuff on the console. 所以我得到了我想要的东西,但另一方面,程序运行时控制台是空白的,这对我来说是一个问题,因为我希望程序在控制台上输出内容。

Is there anyway to get past this ? 反正有没有超过这个?

If I were you I'd have used regular stdout and tee 如果我是你,我会使用常规的stdout和tee

Let's say you have code: simple.py 假设你有代码: simple.py

print("Hello")

You can run it like this 你可以像这样运行它

> python ./simple.py  | tee output.log
Hello
> cat output.log
Hello

And you have both - messages on console and log file. 而且你有两个 - 控制台和日志文件上的消息。

Logger based approach 基于记录器的方法

This is not exactly what you are looking for, but you still can run it such way you will get results in both: console and file 这不是您正在寻找的,但您仍然可以运行它,这样您将获得结果:控制台和文件

import logging

logger = logging.getLogger('simple')
logger.setLevel(logging.INFO)

std_out = logging.StreamHandler()
file_out = logging.FileHandler('file.log')

logger.addHandler(std_out)
logger.addHandler(file_out)

logger.info('Hello from code')

and you will get following 你会得到以下的

> python ./simple.py
Hello from code
> cat file.log
Hello from code

Changing sys.stdout to be a custom stream (file) is a little extreme. 将sys.stdout更改为自定义流(文件)有点极端。 A couple of options: 1. Do the redirection on the command line. 有两个选项:1。在命令行上执行重定向。 If you are using bash (linux / mac / etc) you can pipe the output to the "tee" program, eg 如果你正在使用bash(linux / mac / etc),你可以将输出传递给“tee”程序,例如

python my_program.py | tee logfile.txt

tee is a simple program that takes its input (stdin) and writes it to stdout as well as a file of your choosing. tee是一个简单的程序,它接受输入(stdin)并将其写入stdout以及您选择的文件。

  1. Instead of using print(), create a logging class and use that to print output. 而不是使用print(),创建一个日志类并使用它来打印输出。 Modify your logging class to write to both sys.stdout and your log file, depending on configuration. 修改日志记录类以写入sys.stdout和日志文件,具体取决于配置。 See also the logging docs. 另请参阅日志记录文档。

  2. More advanced and hacky: create your own File implementation that acts like the"tee" program and forwards its write() etc. calls to two underlying files: sys.stdout and your file for the log file. 更高级和hacky:创建自己的File实现,其作用类似于“tee”程序,并将其write()等调用转发给两个底层文件:sys.stdout和日志文件的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM