Display a countdown for the python sleep function

后端 未结 7 1190
一生所求
一生所求 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:37

    time.sleep() may return earlier if the sleep is interrupted by a signal or later (depends on the scheduling of other processes/threads by OS/the interpreter).

    To improve accuracy over multiple iterations, to avoid drift for large number of iterations, the countdown may be locked with the clock:

    #!/usr/bin/env python
    import sys
    import time
    
    for i in reversed(range(1, 1001)):
        time.sleep(1 - time.time() % 1) # sleep until a whole second boundary
        sys.stderr.write('\r%4d' % i)
    

提交回复
热议问题