Writing terminal output to terminal and to a file?
<p>I have different functions which is giving string and text output in the terminal during excecution of the function. The command I have used is <code>sys.stdout.write</code></p>

<p>In one of the function I am creating a file and calling those functions mentioned above. When running this function I need to write all the <code>sys.output.write</code> output from different functions in the file as well as to the terminal.</p>

<p>Sample code is like:</p>

<pre><code>def func1():
  sys.stdout.write('A')
  sys.stdout.write('B')

def func2():
  sys.stdout.write('C')
  sys.stdout.write('D')
def main():
  fileName=open("log.txt","W+")
  func1()
  func2()
  --------------------
  # need output ABCD both in terminal and write in logfile as well
  # unfortunately cannot change anything in func1() and func2()
</code></pre>

<p>Use a context manager to create a wrapper that writes to a file and <code>stdout</code>:</p>

<pre><code>class Tee(object):
    def __init__(self, log_file_name, stdout):
        self.log_file_name = log_file_name
        self.stdout = stdout

    def __enter__(self):
        self.log_file = open(self.log_file_name, 'a', 0)
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.log_file.close()

    def write(self, data):
        self.log_file.write(data)
        self.stdout.write(data)
        self.stdout.flush()

def main():
    with Tee('log.txt', sys.stdout) as sys.stdout:
        func1()
        func2()
</code></pre>

<p>Don't forget to flush <code>stdout</code> after each write as it is buffered.</p>

python