> Firstly when I first started off I came across a problem where everything I sent
> back (via a print statement) came up only after the script had finished, a quick
> post on the kmuddy led me to using sys.stdout.flush() after each print
> statement, but it was also mentioned that in other languages it's possible to
> disable the output buffer entirely.
> Mentioned in perl: ,$|=1;
> and in C/C++ as: setvbuf (stdout, 0, _IONBF, 0);
> How do I do this in python?
You can skip buffering for a whole python process using
"python -u" (or #!/usr/bin/env python -u etc) or by setting
the environment variable PYTHONUNBUFFERED.
You could also replace sys.stdout with some other stream
like wrapper which does a flush after every call.
Something like this (not really tested) might work...but
there are probably problems that could pop up. For instance,
I don't think it will work in IDLE, since sys.stdout is
already replaced with some funny object there which doesn't
like to be flushed. (This could be considered a bug in IDLE
though.)
>>> class Unbuffered:
.. def __init__(self, stream):
.. self.stream = stream
.. def write(self, data):
.. self.stream.write(data)
.. self.stream.flush()
.. def __getattr__(self, attr):
.. return getattr(self.stream, attr)
..
>>> import sys
>>> sys.stdout=Unbuffered(sys.stdout)
>>> print 'Hello'
Hello
Here, we replace sys.stdout with an object that
will make a flush after every write, but will
delegate everything else to the buffer it was
initiated with.
Of course, this is (if it works :) a more generic
solution that can be used for a lot more than flushing
buffers. For instance, it could turn your output into
pig latin or convert text to some different code page.
--
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65
http://www.thinkware.se/ mailto:magnus at thinkware.se