Search code examples
python-3.xtextterminal

How can I print a dynamic text in terminal using Python?


I want to print a constant message in the form of:

Time remaining: X Seconds

Where X will be a count-down number. But I don't want to have an output like:

Time remaining: 5 Seconds
Time remaining: 4 Seconds
Time remaining: 3 Seconds
Time remaining: 2 Seconds ...

I want only the number to change in the same text line. Is it possible using escape sequences or other way?


Solution

  • Yes you can!

    Please refer to the answer found here

    The code has been modified a little to look more like you want, and to use the more recent string formatting.

    from time import sleep
    import sys
    
    for i in range(10):
        sys.stdout.write("\rTime remaining: {} Seconds".format(i))
        sys.stdout.flush()
        sleep(1)
    print '\n'