Python Progress Bar

后端 未结 30 2225
礼貌的吻别
礼貌的吻别 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:15

    If your work can't be broken down into measurable chunks, you could call your function in a new thread and time how long it takes:

    import thread
    import time
    import sys
    
    def work():
        time.sleep( 5 )
    
    def locked_call( func, lock ):
        lock.acquire()
        func()
        lock.release()
    
    lock = thread.allocate_lock()
    thread.start_new_thread( locked_call, ( work, lock, ) )
    
    # This part is icky...
    while( not lock.locked() ):
        time.sleep( 0.1 )
    
    while( lock.locked() ):
        sys.stdout.write( "*" )
        sys.stdout.flush()
        time.sleep( 1 )
    print "\nWork Done"
    

    You can obviously increase the timing precision as required.

提交回复
热议问题