title: Capture stdout from a script?
body: <p>suppose there is a script doing something like this:</p>
  
  <pre><code># module writer.py
  import sys
  
  def write():
      sys.stdout.write("foobar")
  </code></pre>
  
  <p>Now suppose I want to capture the output of the <code>write</code> function and store it in a variable for further processing. The naive solution was:</p>
  
  <pre><code># module mymodule.py
  from writer import write
  
  out = write()
  print out.upper()
  </code></pre>
  
  <p>But this doesn't work. I come up with another solution and it works, but please, let me know if there is a better way to solve the problem. Thanks</p>
  
  <pre><code>import sys
  from cStringIO import StringIO
  
  # setup the environment
  backup = sys.stdout
  
  # ####
  sys.stdout = StringIO()     # capture output
  write()
  out = sys.stdout.getvalue() # release output
  # ####
  
  sys.stdout.close()  # close the stream 
  sys.stdout = backup # restore original stdout
  
  print out.upper()   # post processing
  </code></pre>