[Tutor] Useless: Twiddle prompt w/o curses?

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri Nov 8 16:02:01 2002


On Fri, 8 Nov 2002 Doug.Shawhan@gecits.ge.com wrote:

> For reasons of perversity and foofiness, I desire to create a twiddle prompt
> in python.
>
> http://www.elsewhere.org/jargon/html/entry/twirling-baton.html
>
> The sequence : -/|\-/|\-  interspersed with backspace characters has proven
> to be a tad more difficult to produce on the same line than I thought.
>
> Has anyone got an idea on how to change characters in place in a portable
> way? i.e. not resorting to curses? (Nothing against curses, mind you...)


Hi Doug,

Here's something that works for me:

###
>>> while 1:
...     for ch in r'-/|\-/|\\':
...         print '\b\b' + ch,
...         sys.stdout.flush()
...         time.sleep(0.3)
...
|
###

This uses the 'backspace' character '\b'.  It's an escape character that
moves the cursor back one place, so we can use it to do the animation.  I
did it twice just to be sure.  *grin*


One important part is the sys.stdout.flush() part: without it, it's very
likely that we won't see a thing, because our operating system tries to
optimize printing by waiting till a whole line is laid out --- it
"buffers" the display of a line.  We can override this buffering behavior
by calling flush().


Hope this helps!