[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

print >> to a derived file

iu2

1/15/2008 9:43:00 AM

Hi,

I'm trying to write data to both a file and the console, so I did:

class File_and_console(file):
def write(self, s):
file.write(self, s)
print s,

>>> f = File_and_console('1.txt', 'w')
>>> f.write('hello')
hello
>>> print >>f, 'world'
>>>

the 'write' method works, but 'print >>' doesn't, it writes only to
the file. It doesn't actually call File_and_console.write

Why? How can I fix it?
Thanks
iu2
3 Answers

Ben Fisher

1/15/2008 10:45:00 AM

0

This might have something to do with the class being derived from file.

I've written it so that it doesn't derive from file, and it works.

class File_and_console():
def __init__(self, *args):
self.fileobj = open(*args)
def write(self, s):
self.fileobj.write(s)
print s,

f = File_and_console('testout.tmp','w')
f.write('hello')
print >>f,'hello',


On 1/15/08, iu2 <israelu@elbit.co.il> wrote:
> Hi,
>
> I'm trying to write data to both a file and the console, so I did:
>
> class File_and_console(file):
> def write(self, s):
> file.write(self, s)
> print s,
>
> >>> f = File_and_console('1.txt', 'w')
> >>> f.write('hello')
> hello
> >>> print >>f, 'world'
> >>>
>
> the 'write' method works, but 'print >>' doesn't, it writes only to
> the file. It doesn't actually call File_and_console.write
>
> Why? How can I fix it?
> Thanks
> iu2
> --
> http://mail.python.org/mailman/listinfo/p...
>

iu2

1/15/2008 11:08:00 AM

0

On Jan 15, 12:44 pm, "Ben Fisher" <jamon....@gmail.com> wrote:
> This might have something to do with the class being derived from file.
>
> I've written it so that it doesn't derive from file, and it works.
>
> class File_and_console():
>         def __init__(self, *args):
>                 self.fileobj = open(*args)
>         def write(self, s):
>                 self.fileobj.write(s)
>                 print s,
>
> f = File_and_console('testout.tmp','w')
> f.write('hello')
> print >>f,'hello',
>

Thanks, but that's what I tried first. Then I though it would be nice
if I could just inherit from 'file' and implement this with less code.

Scott David Daniels

1/16/2008 1:46:00 AM

0

iu2 wrote:
> Hi,
>
> I'm trying to write data to both a file and the console, so I did:
>
> class File_and_console(file):
> def write(self, s):
> file.write(self, s)
> print s,
>>>> f = File_and_console('1.txt', 'w')
....

Always use the same method for writing, or you will get weird results.
If you think the above works, try:
for char in 'sample': f.write(char)

class MultiWrite(object):

def write(self, text):
for dest in self._files:
dest.write(text)

def __init__(self, *files):
self._files = files

def close(self):
for dest in self._files:
dest.close()


f1 = MultiWrite(open('1.txt', 'w'), sys.stdout)

--Scott David Daniels
Scott.Daniels@Acm.Org