if self.stdout:
    sys.stdout = open(self.stdout, 'w')
if self.stderr:
    if self.stderr == self.stdout:
        sys.stderr = sys.stdout
else:
    sys.stderr = open(self.stderr, 'w')

def __exit__(self, exc_type, exc_value, traceback):
    sys.stdout = self.sys_stdout
sys.stderr = self.sys_stderr
IPython: redirecting output of a Python script to a file (like bash >)