Python how to make simple animated loading while process is running

前端 未结 6 1787
广开言路
广开言路 2020-12-13 03:30

This is pretty much what I have right now:

import time
import sys

done = \'false\'
#here is the animation
def animate():
    while done == \'false\':
               


        
6条回答
  •  不思量自难忘°
    2020-12-13 03:50

    Use a thread:

    import itertools
    import threading
    import time
    import sys
    
    done = False
    #here is the animation
    def animate():
        for c in itertools.cycle(['|', '/', '-', '\\']):
            if done:
                break
            sys.stdout.write('\rloading ' + c)
            sys.stdout.flush()
            time.sleep(0.1)
        sys.stdout.write('\rDone!     ')
    
    t = threading.Thread(target=animate)
    t.start()
    
    #long process here
    time.sleep(10)
    done = True
    

    I also made a couple of minor modifications to your animate() function, the only really important one was adding sys.stdout.flush() after the sys.stdout.write() calls.

提交回复
热议问题