我在我的程序中使用time.sleep(10)。我运行程序时可以在shell中显示倒计时吗?
>>>run_my_program()
tasks done, now sleeping for 10 seconds
然后我想要它做10,9,8,7 ....
这可能吗?
答案 0 :(得分:20)
你总能做到
#do some stuff
print 'tasks done, now sleeping for 10 seconds'
for i in xrange(10,0,-1):
time.sleep(1)
print i
这个片段有一些令人讨厌的功能,每个号码都会在换行符上打印出来。为避免这种情况,您可以
import sys
import time
for i in xrange(10,0,-1):
sys.stdout.write(str(i)+' ')
sys.stdout.flush()
time.sleep(1)
答案 1 :(得分:7)
您可以执行倒计时功能,例如:
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)
回车\r
和逗号,
会使打印保持在同一行(每个倒计时值都避免一行)
随着秒数的减少,pad_str将确保最后一行被空格覆盖,而不是在输出缩短时留下最后一个字符。
最后一次打印用完成消息覆盖最后一条状态消息并递增输出行,因此有延迟的证据。
答案 2 :(得分:6)
这是在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")
这会在每个循环中写入前一行。
答案 3 :(得分:2)
这是我在我的第一个python课程中学到的东西,我们玩过[" /"," - "," | "," \"," |"]但原则是相同的:
import time
for i in reversed(range(0, 10)):
time.sleep(1)
print "%s\r" %i,
答案 4 :(得分:1)
当然,只需编写一个打印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)
答案 5 :(得分:1)
这是我做的一个:
import time
a = input("How long is the countdown?")
while a != 0:
print a
time.sleep(1)
a = a-1
最后如果你和其他人你可以发出警报或其他什么。
答案 6 :(得分:1)
time.sleep()
可能会提前返回。
为了提高多次迭代的准确性,为了避免大量迭代的漂移,倒计时可能会被时钟锁定:
#!/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)
答案 7 :(得分:1)
从控制台清除最后一个数字的简单解决方案。
import time
for i in range(10,0,-1):
print(f"{i}", end="\r", flush=True)
time.sleep(1)
默认情况下,print 函数设置 end="\n"
,这意味着对 print 的后续调用将打印在新行上。您可以将其更改为 end=“\r”
以在每次调用 (https://www.codespeedy.com/how-does-carriage-return-work-in-python/) 后替换输出。
此外,使用 flush
意味着您不必担心缓冲问题 (What does print()'s `flush` do?)。
这是它的样子:
答案 8 :(得分:0)
这个是亚秒级的:
print()
_k = 0.5 # ensure k != _k first time round (as k will be integer)
print('Starting in ')
while _k > 0:
k = round(event_timestamp - time())
if k != _k:
print(f'\r{k} ', end='', flush=True)
_k = k
sleep(0.1)
print('boom')
注意 f'\r{k} '
中的尾随空格。因此,如果我们从 100
转到 99
或从 10
转到 9
,它会清除第二个数字。
它也不需要 import sys
。
sleep(0.0003)
如果你想要毫秒精度。
答案 9 :(得分:0)
如果你不限制自己睡觉,那么(礼貌automatetheboringstuff),pyautogui 有一个漂亮的倒计时功能:
import pyautogui
print('Starting in ', end=''); pyautogui.countdown(3)