def stdouterrlog(logfile):
    with open(logfile, 'wb') as lf:
        stdout = sys.stdout
stderr = sys.stderr
sys.stdout = lf
sys.stderr = lf
yield lf
sys.stdout = stdout
sys.stderr = stderr
Logging stdout and stderr to log file using Python 'with' statement