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

3 thoughts on “Store standard output on a variable in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s