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
Thank you for an useful post. It really saved my time.
Does not seem to work with Python 3.3 at the moment.
I’ve edited to show both on Python2 and Python3 (the StringIO class is now on the “io” module)
(Sorry for the delay)
Great! I was exactly locking for that. Thank you very much.
getting error process_string is not found
… You’re supposed to make your own process string function.
Not a complete tutorial then.
it’s great! Thank you.. and if i want to show data from standard out as a real time data, what should i do?
Very useful! thanks
Pingback: Redirect output of bpy.ops.render.render() to variable – GrindSkills