Skip to content

Instantly share code, notes, and snippets.

@jasonbartz
Created January 17, 2014 19:38
Show Gist options
  • Save jasonbartz/8480004 to your computer and use it in GitHub Desktop.
Save jasonbartz/8480004 to your computer and use it in GitHub Desktop.
A simple decorator to redirect stdout somewhere else
"""
A simple decorator to redirect stdout somewhere else
# Example usage
```
def my_write_func(text, **kwargs):
// do something with text
pass
@redirect_stdout
def grabthar():
print "By Grabthar's Hammer, by the sons of Warvan, you shall be avenged."
grabthar()
```
"""
import sys
from cStringIO import StringIO
class redirect_stdout(object):
def __init__(self, write_func, **kwargs):
"""Init and set vars"""
self.write_func = write_func
self.kwargs = kwargs
def __call__(self, function):
"""Call the function"""
def wrapped_function(*args, **kwargs):
try:
sys.stdout = StringIO()
function_to_exec = function(*args, **kwargs)
out = sys.stdout.getvalue()
self.write_func(out, **kwargs)
finally:
sys.stdout.close()
sys.stdout = sys.__stdout__
return function_to_exec
return wrapped_function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment