0

So for analysis, I want to save everything the scripts outputs on the console/terminal, and for that I used 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 ?

Stefan
  • 375
  • 1
  • 9
  • 24
  • So, you want to output to both console and file? – Blorgbeard May 23 '19 at 16:34
  • @Blorgbeard exactly – Stefan May 23 '19 at 16:34
  • Some options here: https://stackoverflow.com/questions/616645/how-to-duplicate-sys-stdout-to-a-log-file – Blorgbeard May 23 '19 at 16:36
  • assign `stdout` to other variable `original_stdout = sys.stdout` and use `original_stdout.write("text\n")` to write on console. OR if you do this because you want to redicrect `print()` to file then you can use `print("text", file=file_handler)`. OR use module `logging` to send messages on screen and save in file. – furas May 23 '19 at 17:09

2 Answers2

0

If I were you I'd have used regular stdout and tee

Let's say you have code: 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
Oo.oO
  • 12,464
  • 3
  • 23
  • 45
0

Changing sys.stdout to be a custom stream (file) is a little extreme. A couple of options: 1. Do the redirection on the command line. If you are using bash (linux / mac / etc) you can pipe the output to the "tee" program, e.g.

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.

  1. Instead of using print(), create a logging class and use that to print output. Modify your logging class to write to both sys.stdout and your log file, depending on configuration. 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.

ajfabbri
  • 421
  • 3
  • 5