Logging stdout and stderr to log file using Python 'with' statement
<p>I want to log the std output of a chunk of Python code to a file, using the 'with' statement:</p>

<pre><code>with log_to_file('log'):
    # execute code
</code></pre>

<p>Is the easiest way to do this to define the <code>log_to_file</code> manually, e.g.:</p>

<pre><code>import sys

class log_to_file():
    def __init__(self, filename):
        self.f = open(filename, 'wb')

    def __enter__(self):
        self.stdout = sys.stdout
        self.stderr = sys.stderr
        sys.stdout = self.f
        sys.stderr = self.f

    def __exit__(self, type, value, traceback):
        sys.stdout = self.stdout
        sys.stderr = self.stderr
</code></pre>

<p>or is there a built-in class that can do this already?</p>
