[Python-bugs-list] [ python-Bugs-524066 ] Override sys.stdout.write newstyle class
noreply@sourceforge.net
noreply@sourceforge.net
Thu, 07 Mar 2002 06:59:37 -0800
Bugs item #524066, was opened at 2002-02-28 22: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
----------------------------------------------------------------------
Comment By: Gordon B. McMillan (gmcm)
Date: 2002-03-07 14: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