title: Redirect both 'print()' and 'os.system' to log file while maintaining the original output in console
body: <p>I've been reading about <a href="https://stackoverflow.com/questions/2513479/redirect-prints-to-log-file">redirect prints to log file</a>, however I did not understand why the accepted answer did not really work as expected.</p>
  
  <p>The original code was in Python2, I've modified it a little bit as I'm working on Python3.</p>
  
  <p><strong>Accepted Answer</strong>:
  <a href="https://stackoverflow.com/a/2513511/9013730">https://stackoverflow.com/a/2513511/9013730</a></p>
  
  <pre><code>import os
  
  def test():
      cmd = 'ver'
      print("1. Running command:",cmd)    # message.log only, NOT in console
      os.system(cmd)                      # This appear in console only, but not in message.log
      print('3. Done')                    # message.log only, NOT in console
  
  import sys
  old_stdout = sys.stdout
  log_file = open("message.log","w")
  sys.stdout = log_file
  print("This will be written to message.log")    # message.log only, NOT in console
  test()
  sys.stdout = old_stdout
  log_file.close()
  </code></pre>
  
  <p><strong>Console Output</strong></p>
  
  <p>As you can see, only <code>os.system(cmd)</code> printed out in console and I did not see it in message.log Output.</p>
  
  <pre><code>Microsoft Windows
  </code></pre>
  
  <p><strong>message.log Output</strong></p>
  
  <p>When I checked message.log output, <code>os.system(cmd)</code> was not there.</p>
  
  <pre><code>This will be written to message.log
  1. Running command: ver
  3. Done
  </code></pre>
  
  <p>Would it be possible to produce similar (exact) output in both console and message.log?</p>
  
  <p><strong>Desired Output in both console and message.log</strong></p>
  
  <pre><code>This will be written to message.log
  1. Running command: ver
  Microsoft Windows
  3. Done
  </code></pre>