Python Progress Bar

后端 未结 30 2635
礼貌的吻别
礼貌的吻别 2020-11-22 06:13

How do I use a progress bar when my script is doing some task that is likely to take time?

For example, a function which takes some time to complete and returns

30条回答
  •  执笔经年
    2020-11-22 07:10

    I like this page.

    Starts with simple example and moves onto a multi-threaded version. Works out of the box. No 3rd party packages required.

    The code will look something like this:

    import time
    import sys
    
    def do_task():
        time.sleep(1)
    
    def example_1(n):
        for i in range(n):
            do_task()
            print '\b.',
            sys.stdout.flush()
        print ' Done!'
    
    print 'Starting ',
    example_1(10)
    

    Or here is example to use threads in order to run the spinning loading bar while the program is running:

    import sys
    import time
    import threading
    
    class progress_bar_loading(threading.Thread):
    
        def run(self):
                global stop
                global kill
                print 'Loading....  ',
                sys.stdout.flush()
                i = 0
                while stop != True:
                        if (i%4) == 0: 
                            sys.stdout.write('\b/')
                        elif (i%4) == 1: 
                            sys.stdout.write('\b-')
                        elif (i%4) == 2: 
                            sys.stdout.write('\b\\')
                        elif (i%4) == 3: 
                            sys.stdout.write('\b|')
    
                        sys.stdout.flush()
                        time.sleep(0.2)
                        i+=1
    
                if kill == True: 
                    print '\b\b\b\b ABORT!',
                else: 
                    print '\b\b done!',
    
    
    kill = False      
    stop = False
    p = progress_bar_loading()
    p.start()
    
    try:
        #anything you want to run. 
        time.sleep(1)
        stop = True
    except KeyboardInterrupt or EOFError:
             kill = True
             stop = True
    

提交回复
热议问题