0

I'm trying to make countdown program with python. I want to turn that into it removes last printed line, so i can print new second.

import time

def countdown():
    minute = 60
    while minute >= 0:
        m, s = divmod(minute, 60)
        time_left = str(m).zfill(2) + ':' + str(s).zfill(2)
        print(time_left)
        time.sleep(1) 
        minute -= 1

countdown()

I am running python 2.7.13 on Raspberry Pi.

Veikka
  • 11
  • 2
  • 3
    Possible duplicate of [output to the same line overwriting previous output ? python (2.5)](https://stackoverflow.com/questions/4897359/output-to-the-same-line-overwriting-previous-output-python-2-5) – Liora Haydont May 07 '18 at 20:25
  • 2
    Possible duplicate of [How to overwrite the previous print to stdout in python?](https://stackoverflow.com/questions/5419389/how-to-overwrite-the-previous-print-to-stdout-in-python) – Anton vBR May 07 '18 at 20:26

2 Answers2

0

You could write directly to stdout, instead of using print. And the \r character will go to the beginning of the line, not the next line.

 import time
 import sys

 def countdown():
     minute = 60
     while minute >= 0:
         m, s = divmod(minute, 60)
         time_left = str(m).zfill(2) + ':' + str(s).zfill(2)
         sys.stdout.write("%s\r" % time_left)
         sys.stdout.flush()
         time.sleep(1) 
         minute -= 1
eduffy
  • 35,646
  • 11
  • 90
  • 90
0

Try the following (it's made in python2):

import time, sys

def countdown(totalTime):
    try:
        while totalTime >= 0:
            mins, secs = divmod(totalTime, 60)
            sys.stdout.write("\rWaiting for {:02d}:{:02d}  minutes...".format(mins, secs))
            sys.stdout.flush()
            time.sleep(1)
            totalTime -= 1
            if totalTime <= -1:
                print "\n"
                break
    except KeyboardInterrupt:
        exit("\n^C Detected!\nExiting...")

Call it like this: countdown(time) For example: countdown(600) for 10 minutes.

Sanduuz
  • 36
  • 1
  • 6