Display a countdown for the python sleep function

后端 未结 7 1142
一生所求
一生所求 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 03:02

    You can do a countdown function like:

    import sys
    import time
    
    def countdown(t, step=1, msg='sleeping'):  # in seconds
        pad_str = ' ' * len('%d' % step)
        for i in range(t, 0, -step):
            print '%s for the next %d seconds %s\r' % (msg, i, pad_str),
            sys.stdout.flush()
            time.sleep(step)
        print 'Done %s for %d seconds!  %s' % (msg, t, pad_str)
    

    The carriage return \r and the comma , will keep the print in the same line (avoiding one line for each countdown value)

    As the number of seconds decreases, the pad_str will ensure the last line is overwritten with spaces instead of leaving the last character(s) behind as the output shortens.

    The final print overwrites the last status message with a done message and increments the output line, so there is evidence of the delay.

    0 讨论(0)
提交回复
热议问题