[Python-bugs-list] [ python-Bugs-524066 ] Override sys.stdout.write newstyle class

noreply@sourceforge.net noreply@sourceforge.net
Thu, 28 Feb 2002 14:06:22 -0800


Bugs item #524066, was opened at 2002-02-28 16:06
You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=524066&group_id=5470

Category: Type/class unification
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Matthew Cowles (mdcowles)
Assigned to: Nobody/Anonymous (nobody)
Summary: Override sys.stdout.write newstyle class

Initial Comment:
Posted to python-help.

Using Python 2.2, I'm trying to create a file-like class that write in a file and on standard output. But I'm having a problem, since 'print' statement doesn't seems to call the write method when I  assign an object inheriting from 'file' to 'sys.stdout'.

The following code shows the problem:

>>> import sys
>>> class test (file):
...	def write (_, s):
...		sys.__stdout__.write (s)
...
>>> log = test ('log', 'r')
>>> log.write ('hello\n')
hello
>>> sys.stdout = log
>>> print 'hello'
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IOError: [Errno 9] Bad file descriptor

As you can see, I'm getting error, since Python try to write to a file opened in read-only mode, and so don't call my redefined 'write' method ...

On the contrary, when using a standard class, only defining the 'write' method, I'm getting the desired behaviour.

>>> import sys
>>> class test:
...	def write (_, s):
...		sys.__stdout__.write (s)
...
>>> log = test ()
>>> log.write ('hello\n')
hello
>>> sys.stdout = log
>>> print 'hello'
hello


----------------------------------------------------------------------

You can respond by visiting: 
http://sourceforge.net/tracker/?func=detail&atid=105470&aid=524066&group_id=5470