[Tutor] TypeError in class destructor
Mark Lybrand
mlybrand at gmail.com
Sat Dec 10 18:54:15 CET 2011
I am working on the Files chapter of Dive into Python 3, and have
implemented the example script at the end of this message. The first input
prints to the terminal as expected, the second value prints to the file as
expected. Then the script tries to destroy in the class instance and bombs
with:
TypeError: __exit__() takes exactly 1 positional argument (4 given)
Exception ValueError: 'I/O operation on closed file.' in <_io.TextIOWrapper
name
='out.log' mode='w' encoding='utf-8'> ignored
and the final input is, naturally, never printed.
Is the example wrong, or is this something to do with how Windows handles
stdout that is causing this not to work as designed? I am using Python 3.2
on Windows Vista Home Premium.
import sys
class RedirectStdoutTo:
def __init__(self, out_new):
self.out_new = out_new
def __enter__(self):
self.out_old = sys.stdout
sys.stdout = self.out_new
def __exit__(self):
sys.stdout = self.out_old
print('A')
with open('out.log', mode='w', encoding='utf-8') as a_file,
RedirectStdoutTo(a_file):
print('B')
print('C')
--
Mark :)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111210/fd792e43/attachment.html>
More information about the Tutor
mailing list