from io import StringIO
buffer = StringIO()
sys.stdout = buffer
exec("print 'Hello, World!'")
sys.stdout = sys.__stdout__
print(buffer.getvalue())
Execute a block of python code with exec, capturing all its output?