0

I know how to redirect stdout into a file:

import sys
sys.stdout = open('log.txt', 'w')
print 'test'

This will create a log.txt where test will be written in it. However, test will not be print in stdout.

How can i print and redirect test in both terminal and file without changing every print statement in the program.

PS: I know that redirecting sys.stdout is bad (but i still need to do it)

Phong
  • 6,600
  • 4
  • 32
  • 61

2 Answers2

0

The tee unix command reads standard input and writes it to both standard output and one or more files. In might be an option for you to redirect the output of your script to tee.

SylvainD
  • 1,743
  • 1
  • 11
  • 27
0

You should probably run your entire script piped to tee: python hello.py | tee logfile.txt . Altering sys.stdout to a file-like object which contains the splitting functionality is possible, but won't cover subprocesses run by your script. You then need to use the second process via pipe, and by then there's no need to reinvent the wheel.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26