Skip to content
Advertisement

Python: How do I display a timer in a terminal

I’m new to python programming and using ubuntu to do so. In a program I have done I used a delay of 1 minute until it executes the code again. How can I program a timer to be displayed in the terminal based on the value of the delayed time? Thanks in advance…

Advertisement

Answer

The simplest way is as follows.

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

"r" returns the text cursor to the beginning of the line, so that you can overwrite what you’re previously written. Because typically output isn’t written until a newline ("n"), you need to manually .flush() the output stream.

Because the line isn’t being cleared, we need to ensure that each new line of output is long enough to cover up the existing line.

The curses module has tools for more advanced terminal output, but is more complicated to use.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement