Created
January 17, 2014 19:38
-
-
Save jasonbartz/8480004 to your computer and use it in GitHub Desktop.
A simple decorator to redirect stdout somewhere else
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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