title: redirect sys.stdout to a file without buffering in Python 3
body: <p>I have a script that writes to a log file. In Python 2, my quick solution to allow tailing/viewing of the log as it progressed was by assigning <code>sys.stdout</code> to a file object with buffering set to 0:</p>
  
  <pre><code>original_stdout = sys.stdout
  sys.stdout = open(log_file, 'w', 0)
  </code></pre>
  
  <p>Once set, any print statements in the script's functions redirect to the log file very nicely.</p>
  
  <p>Running the 2to3-converted version under Python 3 gives the following error: <code>ValueError: can't have unbuffered text I/O</code>. Changing the <code>'w'</code> above to <code>'wb'</code> solves that, so the structure of the block is</p>
  
  <pre><code>original_stdout = sys.stdout
  sys.stdout = open(log_file, 'wb', 0)
  print("{}".format(first_message))
  </code></pre>
  
  <p>but now the first print statement errors with <code>TypeError: 'str' does not support the buffer interface</code>. I tried explicitly casting the string to bytes</p>
  
  <pre><code>print(bytes("{}".format(first_message), "UTF-8"))
  </code></pre>
  
  <p>but that produces the same <code>TypeError</code> as before.</p>
  
  <p>What is the easiest way to write unbuffered text to a file in Python 3?</p>