import sys
from contextlib import contextmanager
import functools
@contextmanager
def stdout(filename):
with open(filename, 'a') as outfile:
stdout_old = sys.stdout
sys.stdout = outfile
yield
sys.stdout = stdout_old
def redirect_stdout(f, filename):
@functools.wraps(f)
def wrapper(*args, **kwargs):
with stdout(filename):
f(*args, **kwargs)
return wrapper
def testfn():
print 'hello'
testfn() # vypise hello na standartni vystup
testfn = redirect_stdout(testfn, 'somefile.txt')
testfn() # vypise hello do souboru somefile.txt