print >> to a derived file

I

iu2

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,

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
 
B

Ben Fisher

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',
 
I

iu2

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.
 
S

Scott David Daniels

iu2 said:
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,
....

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
(e-mail address removed)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,235
Latest member
Top Crypto Podcasts_

Latest Threads

Top