Can I write to terminal and a given file with one command in Python?
Question: I have seen this question answered in reference to Bash, but can't find one
for Python. Apologies if this is repeating something.

Is it possible to print to the terminal and an output file with one command?
I'm familiar with using `print >>` and `sys.stdout = WritableObject`, but I'd
like to avoid having to double print commands for each line I want logged.

I'm using Python 2.6, just in case such knowledge is necessary.

More importantly, I want this to run on a Windows-based system using IDLE's
command line. So, in essence, I want the python script to report to IDLE's
terminal and a given log file.

**EDIT** : For anyone who finds this and decides to go with the answer I
chose, if you need help understanding context managers (like I did), I
recommend Doug Hellman's Python Modules of the Week for clarification. [This
one details the context
library.](http://www.doughellmann.com/PyMOTW/contextlib/index.html "This one
details context managers.") For help with decorators [see this Stack Overflow
question's answers.](http://stackoverflow.com/questions/739654/understanding-
python-decorators)


Answer: Replace `sys.stdout`.

    
    
    class PrintAndLog(object):
        def __init__(self, fileOrPath): # choose which makes more sense
            self._file = ...
    
        def write(s):
            sys.stdout.write(s)
            self._file.write(s)
    
        def close(self):
            self._file.close()
        # insert wrappers for .flush, .writelines
    
    _old_stdout = sys.stdout
    sys.stdout = PrintAndLog(f)
    ... # print and stuff
    sys.stdout = _old_stdout
    

Can be put into a context manager (this is at least the third time I see
something like this on SO alone...):

    
    
    from contextlib import contextmanager
    
    @contextmanager
    def replace_stdout(f):
        old_stdout = sys.stdout
        try:
            sys.stdout = PrintAndLog(f)
            yield
        finally:
            sys.stdout = old_stdout
    

