title: Python: Redirect various output sections to separate variables
body: <p>I'm trying to create a mechanism to redirect <code>print</code> outputs to a number of variables. Following code simulates what I'm looking for :-</p>
  <pre><code>import sys
  import io
  
  class MultiOut(object):
      def __init__(self, stream_out):
          self.terminal = sys.stdout
          self.output = stream_out
      def write(self, message):
          self.terminal.write(message)
          self.output.write(message)
      def flush(self):
          self.terminal.flush()
          self.output.flush()
  
  vals = {'a1': io.StringIO(), 'a2': io.StringIO(), 'a3': io.StringIO()}
  
  for i,val in enumerate(vals):
      sys.stdout = MultiOut(vals[val])
      [print(x**i, end=' ') for x in range(11)]
      print(&quot;\n&quot;)
  
  with open('temp.txt', 'w') as f:
      for x in vals:
          f.write(f&quot;{x} :-\n&quot;)
          f.write(vals[x].getvalue())
          f.write(f&quot;{'='*50}\n&quot;)
  </code></pre>
  <p>File Output (tmp.txt) :-</p>
  <pre><code>a1 :-
  1 1 1 1 1 1 1 1 1 1 1 
  
  0 1 2 3 4 5 6 7 8 9 10 
  
  0 1 4 9 16 25 36 49 64 81 100 
  
  ==================================================
  a2 :-
  0 1 2 3 4 5 6 7 8 9 10 
  
  0 1 4 9 16 25 36 49 64 81 100 
  
  ==================================================
  a3 :-
  0 1 4 9 16 25 36 49 64 81 100 
  
  ==================================================
  </code></pre>
  <p>What I'm trying to do here is to redirect various 'sections' of the outputs to different variables of <code>vals - a1, a2, a3</code> and dump all the outputs to the terminal. Strangely, each successive variable contains data starting from that point till the end. Is there a way to avoid this issue and save each section in a different variable ?</p>