0

I am creating a command line interface in python and I need to use a countdown and make it visible to the user, so I have coded this function below:

import sys
from time import sleep

def secondsCountdown():
    remainingSeconds = 10

    while (remainingSeconds >= 0):  
        secondsString: str = "[" + str(remainingSeconds) + " seconds]"

        if (remainingSeconds > 0):
            print(secondsString, end="\r") # print line and delete the previous one
            sleep(1)
        elif (remainingSeconds == 0):
            print(secondsString) # only print line

        remainingSeconds -= 1

the code itself works fine, but when the previous value is 'deleted' and the new one is printed, an extra square bracket is displayed in the new line at the end, like this example:

[9 seconds]] ## problem

[9 seconds] ## expected result

I tried to insert '\n' at the end of the 'secondsString' string but somehow this causes the code to stop deleting the previous line. I really don't know how to fix it. I hope for your help.

Thanks in advance.

st4ticv0id
  • 39
  • 6
  • Does this answer your question? [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) – shriakhilc Jan 15 '22 at 18:07
  • The main reason for remaining character is that your initial print with 10 is 1 character longer than the one with 9 and below. So it only overwrites as much as the new text length and leaves a trailing bracket. Check out the answers in the linked question for ways to clear the entire line. – shriakhilc Jan 15 '22 at 18:08
  • Unfortunately I tried to adapt my code by using '\x1b[1K\r' instead of '\r', as explained in the link, to clear the whole line to the end but the result was that no strings were printed out. In any case you have been very helpful to understanding that the problem was in the length of the string. I will look for a solution, thank you very much! – st4ticv0id Jan 15 '22 at 21:02
  • Yes, that didn't work for me either. It seems to be a POSIX only thing, but I didn't quite get that to work too. The idea of printing spaces (a few answers below the accepted one) is probably a safe bet though. It's just your code but overwrite everything with whitespace and then overwrite with actual text. – shriakhilc Jan 15 '22 at 22:10
  • Yeah, in the end I did something like this, but instead of white spaces I used zeros and based on the number of units of the previous number I add zeros in front of the next number. Thanks again, you have been very helpful to me :) – st4ticv0id Jan 16 '22 at 16:08

0 Answers0