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