显示 python sleep 函数的倒计时

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17220128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:48:27  来源:igfitidea点击:

Display a countdown for the python sleep function

pythontimesleepstopwatchcountdowntimer

提问by user1681664

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

我在我的程序中使用 time.sleep(10)。当我运行我的程序时,可以在 shell 中显示倒计时吗?

>>>run_my_program()
tasks done, now sleeping for 10 seconds

and then I want it to do 10,9,8,7....

然后我想让它做 10,9,8,7 ....

is this possible?

这可能吗?

采纳答案by aestrivex

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)

回答by Silas Ray

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:

当然,只需编写一个循环,打印 10 减去迭代计数器,然后让它每次迭代休眠 1 秒并运行 10 次迭代。或者,更灵活:

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)

回答by Saullo G. P. Castro

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 \rand the comma ,will keep the print in the same line (avoiding one line for each countdown value)

回车\r和逗号,将使打印保持在同一行(每个倒计时值避免一行)

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.

随着秒数的减少,pad_str 将确保最后一行被空格覆盖,而不是随着输出的缩短而留下最后一个字符。

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

最后的打印用完成消息覆盖最后一个状态消息并增加输出行,因此有延迟的证据。

回答by Silas Poulson

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.

最后,如果您和其他人可以设置闹钟或其他什么。

回答by jfs

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).

time.sleep()如果睡眠被信号中断或稍后(取决于操作系统/解释器对其他进程/线程的调度),则可能会更早返回。

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)

回答by Azur

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

这是我在第一次 Python 课程中学到的东西,我们使用 ["/","-","|","\","|"] 但原理是相同的:

import time

for i in reversed(range(0, 10)):
    time.sleep(1)
    print "%s\r" %i,

回答by Barkles

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

这是在 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.

这会在每个循环中覆盖上一行。