Problems with sys.stout.flush()

Carl Banks pavlovevidence at gmail.com
Sat May 23 05:38:29 EDT 2009


On May 23, 2:20 am, Joel Ross <jo... at cognyx.com> wrote:
> Carl Banks wrote:
> > On May 22, 10:33 pm, Joel Ross <jo... at cognyx.com> wrote:
> >> Hi all,
>
> >> I'm using python 2.5 and trying to flush the sys.stout buffer with
> >> sys.stout.flush(), but doesn't seem to work. Each time a line is printed
> >>    it appends the one before it I need to clear the output and write a
> >> new output without appending the previous one.
>
> > That's not how streams work, chief.  Once you output (and flush)
> > something you can't un-output it.
>
> > What you probably want to do is to write a carriage return ("\r")
> > which usually causes the cursor to return to the beginning of the
> > line, so that any new text you write overwrites the old text.
>
> > This has nothing to do with flushing; flushing doesn't erase or clear
> > the old input.  Flushing is usually needed for a different reason,
> > however, namely standard output doesn't actually get sent to the
> > console until it sees a newline ("\n") unless you flush the buffer.
>
> > Try to adapt this example to your problem:
>
> > for i in xrange(11):
> >     sys.stdout.write('*'*(10-i) + ' '*i + '\r')
> >     sys.stdout.flush()
> >     time.sleep(2)
>
> Your example prints a new line each time,

Did you run it and observe what happened, or did you just guess what
it actually did?  On my system it doesn't print new lines.


> Doesn't help me with a
> progress bar, do you know of anyway doing it with the print command? My
> progress bars works fine this is the only problem im having with it at
> the moment. any help would be appreciated.

Well, based on the code you posted it doesn't look like your progress
bar is fine.

Anyway, you haven't described the problem you are having very well,
and we can guess what might be wrong but if you want better help
you're going to have to describe your problem more coherently.  Give
us the

1. What code are you actually running (cut-and-paste, please, don't
retype).
2. What do you expect the code to output (type in actual output you
expect to see, not merely a description).
3. What does the code actually output when you run it (cut-and paste,
please, don't just describe).
4. Include any tracebacks if there are any.

In the meantime, I repeat my suggestion that you take my example and
adapt it to what you are doing.

One other note: the print statement is unsuitable for this task
because it always prints a trailing whitespace.  Use sys.stdout.write
for it.


Carl Banks



More information about the Python-list mailing list