显示python sleep函数的倒数计时 [英] Display a countdown for the python sleep function

查看:127
本文介绍了显示python sleep函数的倒数计时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 for 10 seconds

然后我希望它执行10、9、8, 7 ....

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

这可能吗?

推荐答案

您总是可以做

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

这篇关于显示python sleep函数的倒数计时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆