Printing to console, no scroll

mensanator mensanator at aol.com
Wed Jan 14 21:09:05 EST 2004


Harry George <harry.g.george at boeing.com> wrote in message news:<xqxr7y2sq9l.fsf at cola2.ca.boeing.com>...
> "Totte Karlsson" <mtk at qm.com> writes:
> 
> > Hi,
> > How can I print to the console without having it scrolling to a new line for
> > each print statement?
> > I want to print a count down in the console, but for each count it scrolls
> > the screen (of course).
> > 
> >  Is there another way?
> > 
> > Here is the simple script for now
> > 
> > print "Closing window in :"
> > for second in range(10):
> >     time.sleep(1)
> >     print `10-second` +" seconds"
> > 
> > thanks
> > /totte
> > 
> > 
> > 
> > 
> 
> You need to flush after the print statements.  If you have several
> prints (not just 1 as in this example), it is easier to hide in a
> separate function.
> 
> def msg(txt):
>     sys.stdout.write(txt)
>     sys.stdout.flush()
> 
> > for second in range(10):
> >     time.sleep(1)
> >     msg(`10-second` +" seconds ")  #add a space at the end to delimit
> > print    #to finish off the line

That produces

10 seconds 9 seconds 8 seconds 7 seconds 6 seconds 5 seconds 4 seconds 
3 seconds 2 seconds 1 seconds 



This will produce a true countdown - the messages overwite each other:

for sec in range(10):
	time.sleep(1)
	m = "%2d seconds" % (10-sec)
	msg(m + chr(13))

But this will only work on systems that properly handle control 
characters. It works from a Windows command prompt but doesn't from
Idle which shows that silly undefined character box (which I'll 
show here as []). So the Idle output looks like

10 seconds[] 9 seconds[] 8 seconds[] 7 seconds[] 6 seconds[] 
5 seconds[] 4 seconds[] 3 seconds[] 2 seconds[] 1 seconds[] 

which, when copied and pasted into Google, results in

10 seconds
 9 seconds
 8 seconds
 7 seconds
 6 seconds
 5 seconds
 4 seconds
 3 seconds
 2 seconds
 1 seconds

This is the reason why the PROPER way to end a new line is
with a carriage_return + line_feed and not simply line_feed.
It also worked properly from the shell in Cygwin, but I
don't have a real unix or linux system to try it on.



More information about the Python-list mailing list