How to redirect stdout to both file and console with scripting?
python, python-2.7
Solution
You can use shell redirection while executing the Python file:
python foo_bar.py > file
This will write all results being printed on stdout from the Python source to file to the logfile.
Or if you want logging from within the script:
import sys
class Logger(object):
def __init__(self):
self.terminal = sys.stdout
self.log = open("logfile.log", "a")
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
# this flush method is needed for python 3 compatibility.
# this handles the flush command by doing nothing.
# you might want to specify some extra behavior here.
pass
sys.stdout = Logger()
Now you can use:
print "Hello"
This will write "Hello" to both stdout and the logfile.
Problem
I want to run a python script and capture the output on a text file as well as want to show on console. I want to specify it as a property of the python script itself. NOT to use the command `echo "hello world" | tee test.txt` on command prompt every time. Within script I tried: ``` sys.stdout = open('log.txt','w') ``` But this does not show the stdout output on screen. I have heard about logging module but I could not get luck using that module to do the job.