busy indicator

Jonathan Hogg jonathan at onegoodidea.com
Tue Aug 6 13:18:26 CEST 2002


On 6/8/2002 11:16, in article slrnakv8hs.4pp.TuxTrax at fortress.tuxnet,
"TuxTrax" <TuxTrax at fortress.tuxnet.net> wrote:

> I have a python library call in a program that tends to take at least
> five minutes to complete, which is no big deal in and of
> itself. However, I would like to know how to have a "i'm working"
> ticker running, like when a fsck is being done to a mount. You know
> the one. The little twirling ascii graphic that keeps going as long as
> the work is being done so the user knows the system hasn't just
> crashed. This is a CLI app.
> 
> The lib call takes over, and I am to newbie to know how to have it do
> both jobs at once.

Weird, I wrote one of these just yesterday. Though I was explicitly poking
it every-now-and-then to make it spin. If you can't do that you'll need to
use a thread to do the spinning while the library call runs.

Just for fun I've modified mine to use a thread and the code is enclosed
below. I added a couple of variations on the spinning theme as well. The
spinners are only one-shot, so you need to create another to spin some more.

Jonathan


-------------------------------------------------------------------------
import threading, time, sys


class Spinner( threading.Thread ):

    DELAY = 0.1
    DISPLAY = [ '|', '/', '-', '\\' ]
    
    def __init__( self, before='', after='' ):
        threading.Thread.__init__( self )
        self.before = before
        self.after = after
    
    def run( self ):
        write, flush = sys.stdout.write, sys.stdout.flush
        self.running = 1
        pos = -1
        while self.running:
            pos = (pos + 1) % len(self.DISPLAY)
            msg = self.before + self.DISPLAY[pos] + self.after
            write( msg )
            flush()
            write( '\x08' * len(msg) )
            time.sleep( self.DELAY )
        write( ' ' * len(msg) + '\x08' * len(msg) )
        flush()
        
    def stop( self ):
        self.running = 0
        self.join()
    

class BarberPole( Spinner ):
    DISPLAY = [ '|/__/__/__|', '|_/__/__/_|', '|__/__/__/|' ]

class HAL( Spinner ):
    DELAY = 0.2
    DISPLAY = [ ' ', '.', '+', '*', '+', '.', ' ', ' ' ]


def test():

    spinner = Spinner( "[syncing... ", "]" )
    spinner.start()
    time.sleep( 5.0 )
    spinner.stop()
    print "Disks synced."
    
    pole = BarberPole( "Shutting down: " )
    pole.start()
    time.sleep( 5.0 )
    pole.stop()
    print "You may now switch off your computer."
    
    hal = HAL( "[", "]  I'm sorry Dave" )
    hal.start()
    time.sleep( 5.0 )
    hal.stop()
    print "I'm afraid I can't do that."
    

if __name__ == '__main__':
    test()
    




More information about the Python-list mailing list