Display a countdown for the python sleep function

后端 未结 7 1176
一生所求
一生所求 2020-12-30 02:27

I am using time.sleep(10) in my program. Can display the countdown in the shell when I run my program?

>>>run_my_program()
tasks done, now sleeping          


        
7条回答
  •  感情败类
    2020-12-30 02:49

    This is the best way to display a timer in the console for Python 3.x:

    import time
    import sys
    
    for remaining in range(10, 0, -1):
        sys.stdout.write("\r")
        sys.stdout.write("{:2d} seconds remaining.".format(remaining))
        sys.stdout.flush()
        time.sleep(1)
    
    sys.stdout.write("\rComplete!            \n")
    

    This writes over the previous line on each cycle.

提交回复
热议问题