pythonterminaloutputstdout

How to update the same line in terminal output (not print new lines)?


I'm trying to write a simple Python script that updates a line in the terminal every second. Here's my current code:

import sys
from time import sleep

def main():
   for i in range(11):
      sys.stdout.write("The value is %d"%int(i))
      sleep(1)
      sys.stdout.flush()
      
if __name__=="__main__":
   main()

It give me the following output with the delay of 1s between each loop

The value is 0The value is 1The value is 2The value is 3The value is 4The value is 5The value is 6The value is 7The value is 8The value is 9The value is 10

but i need an output like this

This is 1

After 1s, 1 should be replaced by 2 in the same place on the terminal.


Solution

  • It is possible to use the backspace ('\b') character:

    from time import sleep
    
    
    def main():
        print('The value is 0', end='')
        for i in range(1, 11):
            print('\b' + str(i), end='')
            sleep(1)
    
    
    if __name__ == "__main__":
        main()