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="http://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>

<p><code>with FileWrite(..........., sys.stdout) as sys.stdout:</code></p>

<p>You are overwriting <code>sys.stdout</code>, just chose a real name for your file like <code>output</code> or whatever but <code>sys.stdout</code>.</p>

<p>Example:</p>

<pre><code>with FileWrite(..........., sys.stdout) as output:
    output.write('A')
    output.write('B')
sys.stdout.write("test")
</code></pre>

<hr>

<p><strong>EDIT</strong><br>
Since you don't really want to write on the standard output, pass your <code>FileWrite</code> instance as parameter to your methods.</p>

<pre><code>def func1(output):
    output.write('A')

with FileWrite(..........., sys.stdout) as output:
    func1(output)
</code></pre>

<p>Do the same for func2.</p>

python