Python:如何在终端中显示计时器

W. *_*lez 8 python timer

我是python编程的新手,并使用ubuntu这样做.在我做过的程序中,我使用了1分钟的延迟,直到它再次执行代码.如何根据延迟时间的值对终端中显示的计时器进行编程?提前致谢...

小智 18

最简单的方法如下.

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")
Run Code Online (Sandbox Code Playgroud)

"\r"将文本光标返回到行的开头,以便您可以覆盖之前写入的内容.因为通常直到newline("\n")才会写入输出,所以需要手动.flush()输出流.

由于线路未被清除,我们需要确保每个新的输出线足够长以覆盖现有线路.

curses模块具有更高级终端输出的工具,但使用起来更复杂.