Store standard output on a variable in Python

This is a great, hacky trick to get the standard output ( and others like standard error and standard input) in Python

You can “redirect” the standard error changing the sys.stdout module with your own StringIO object. So, you can do something like


from StringIO import StringIO  # Python2
from io import StringIO  # Python3


import sys

# Store the reference, in case you want to show things again in standard output

old_stdout = sys.stdout

# This variable will store everything that is sent to the standard output

result = StringIO()

sys.stdout = result

# Here we can call anything we like, like external modules, and everything that they will send to standard output will be stored on "result"

do_fancy_stuff()

# Redirect again the std output to screen

sys.stdout = old_stdout

# Then, get the stdout like a string and process it!

result_string = result.getvalue()

process_string(result_string)

Easy and very useful!

 

EDITED: Updated to make it work for Python 3.4

10 Comments on “Store standard output on a variable in Python

    • I’ve edited to show both on Python2 and Python3 (the StringIO class is now on the “io” module)

      (Sorry for the delay)

  1. it’s great! Thank you.. and if i want to show data from standard out as a real time data, what should i do?

  2. Pingback: Redirect output of bpy.ops.render.render() to variable – GrindSkills

Leave a comment