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 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!
Thank you for an useful post. It really saved my time.