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

noreply@sourceforge.net noreply@sourceforge.net
Thu, 07 Mar 2002 08:05:29 -0800


Bugs item #524066, was opened at 2002-02-28 17: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: Closed
>Resolution: Invalid
Priority: 5
Submitted By: Matthew Cowles (mdcowles)
>Assigned to: Guido van Rossum (gvanrossum)
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


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

>Comment By: Guido van Rossum (gvanrossum)
Date: 2002-03-07 11:05

Message:
Logged In: YES 
user_id=6380

What happens with mode 'w' is that the print statement
(actually PyFile_WriteObject()) sees that stdout is derived
from a file object, and then takes a shortcut that writes to
the underlying stdio FILE.  It's debatable whether that
could be called a bug in print.

There's so much wrong with the example that I'll just close
it as Invalid.

Try inheriting from object instead of file, then your
example works.

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

Comment By: Gordon B. McMillan (gmcm)
Date: 2002-03-07 09:59

Message:
Logged In: YES 
user_id=4923

Changing the mode to 'w' avoids the exception. However, 
even then "print 'hello'" is silent 
(though "sys.stdout.write('hello\n')" works). So perhaps 
there's a bug in print, but this is a pretty silly use
of subclassing file. And the major complaint (that Python 
throws an exception when you try to write to a file 
opened 'r') is just bogus. Of course it should throw an 
exception.

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

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