Skip to content

Instantly share code, notes, and snippets.

@mostaphaRoudsari
Created June 17, 2017 00:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mostaphaRoudsari/1d961fcd5e8db30032e71b34856511a6 to your computer and use it in GitHub Desktop.
Save mostaphaRoudsari/1d961fcd5e8db30032e71b34856511a6 to your computer and use it in GitHub Desktop.
Redirect print to a variable
"""
Redirect print to a variable.
"""
from cStringIO import StringIO
import sys
originalStdout = sys.stdout
sys.stdout = newStdout = StringIO()
# code ...
print 'covfefe'
print 'covfefe'
sys.stdout = originalStdout
# read the values from StringIO
mystdout.seek(0)
text = mystdout.read()
print text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment