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>

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

def func2():
  sys.stdout.write('C')
  sys.stdout.write('D')



class MyCoolOs:
  def __init__(self,stdout,f):
    self.stdout = stdout
    self.f = f

  def write(self,s):
    self.f.write(s)
    self.stdout.write(s)


def main():
  f=open("log.txt","a")
  sys.stdout = MyCoolOs(sys.stdout,f)
  func1()
  func2()

main()
</code></pre>

python