Entry
print non-symmetry?
Jul 5th, 2000 09:59
Nathan Wallace, Hans Nowak, Snippet 79, Alexander V. Voinov
"""
Packages: files;new_datatypes.streams
"""
"""
> > 2) print only goes to stdout.
> >
> > I think point 2 is significant. Why no option to print to a
> > different stream? Seems awfully unsymmetric.
>
> 'print' seems to mostly just be a pretty wrapper around
> 'sys.stdout.write', and you can certainly call the write method on any
> file object that you want.
Having written a class similar to described below one cound write:
fo1 = OutStream('my_file.txt')
fo2 = OutStream(sys.stdout)
fo3 = OutStream(... whatever has a write method ...)
fo1 << 'Hello World'
fo2 << 'Hello, stdout!'
fo1.close()
# do no close stdout!
I use such a class for more than a year exactly for reasons of (a)symmetry
pointed out by nbecker@fred.net.
(Also take a look at OutString).
Alexander
-----------------------------------
"""
import sys
import cStringIO
class OutStream:
def __init__(self, src):
if isinstance(src, OutS):
self.fo = src.fo
elif type(src) == type(sys.stdout) or hasattr(src, 'write'):
self.fo = src
elif type(src) == type('abc'):
self.fo = open(src, 'w')
def __del__(self):
self.close()
def close(self):
if sys == None or self.fo != sys.stdout:
self.fo.close()
def __lshift__(self, str):
self.fo.write(str)
class OutString(OutStream):
def __init__(self):
self._outb = cStringIO.StringIO()
OutStream.__init__(self, self._outb)
def getvalue(self):
return self._outb.getvalue()