Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How do I display a timer in a terminal

Tags:

python

timer

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

like image 612
W. Gonzalez Avatar asked May 02 '11 02:05

W. Gonzalez


People also ask

Can you put a timer in Python?

A timer in Python is a time-tracking program. Python developers can create timers with the help of Python's time modules. There are two basic types of timers: timers that count up and those that count down.

How do I print a sleep time?

Example 1: Python sleep() import time print("Printed immediately.") time. sleep(2.4) print("Printed after 2.4 seconds.") Here's how this program works: "Printed immediately" is printed.


1 Answers

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.

like image 94
Jeremy Avatar answered Sep 20 '22 09:09

Jeremy