Display a countdown for the python sleep function

后端 未结 7 1141
一生所求
一生所求 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)
    
    0 讨论(0)
  • 2020-12-30 02:43

    Here's one I did:

    import time
    a = input("How long is the countdown?")
    while a != 0:
        print a
        time.sleep(1)
        a = a-1
    

    At the end if you and an else you can put an alarm or whatever.

    0 讨论(0)
  • 2020-12-30 02:45

    This is something that I've learned at one of my first python lessons, we played with ["/","-","|","\","|"] but the principle is the same:

    import time
    
    for i in reversed(range(0, 10)):
        time.sleep(1)
        print "%s\r" %i,
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-30 02:51

    you could always do

    #do some stuff
    print 'tasks done, now sleeping for 10 seconds'
    for i in xrange(10,0,-1):
        time.sleep(1)
        print i
    

    This snippet has the slightly annoying feature that each number gets printed out on a newline. To avoid this, you can

    import sys
    import time
    for i in xrange(10,0,-1):
        sys.stdout.write(str(i)+' ')
        sys.stdout.flush()
        time.sleep(1)
    
    0 讨论(0)
  • 2020-12-30 02:53

    Sure, just write a loop that prints 10 minus the iteration counter, then have it sleep 1 second each iteration and run for 10 iterations. Or, to be even more flexible:

    def printer(v):
        print v
    def countdown_timer(duration, step=1, output_function=printer,
                        prompt='Waiting {duration} seconds.'):
        output_function(prompt.format(duration=duration))
        for i in xrange(duration/step):
            output_function(duration - step * i)
    
    0 讨论(0)
提交回复
热议问题