context manager I/O operation in file
<p>I am using a context manager to wrap the text which would show in terminal and write to file at the same time.</p>

<p>I faced this problem and got the solution, please check
<a href="https://stackoverflow.com/questions/39629435/writing-terminal-output-to-terminal-and-to-a-file">Writing terminal output to terminal and to a file?</a></p>

<p>Cannot change the functions (etc. func1 and func2) problem is after the 'with' statement any output as sys.stdout.write its showing value error: I/O operation in closed file</p>

<p>sample code:</p>

<pre><code>import sys, datetime

class FileWrite(object):
    def __init__(self,log_file_name, stdout):

        self.log_file_name = log_file_name
        self.stdout = stdout

    def __enter__(self):
        self.log_file = open(self.log_file_name, 'a', 0)
        return self

    def __exit__(self, exc_type, exc_value, exc_traceback):
        self.log_file.close()

    def write(self, data):
        self.log_file.write(data)
        self.stdout.write(data)
        self.stdout.flush()
def func1():
     sys.stdout.write('A')
def func2():
     sys.stdout.write('B')
def main():
    with FileWrite(..........., sys.stdout) as sys.stdout:
        func1()
        func2()



    sys.stdout.write('test')

main()
............................
# both output A and B is showing in terminal and writing in file
............................
# writing 'test' only in terminal......
I/O operation in closed file
</code></pre>