Search code examples
pythonpython-2.7carriage-return

"\r" is leaving characters from previous line


Example:

sys.stdout.write("\raaaa")
sys.stdout.flush()
sys.stdout.write("\rbb")
sys.stdout.flush()
# output: bbaa

so \r is returning to the begining of the line overwriting only characters within the new string range, is there any solution to this problem without using spaces to overwrite the rest characters ?

ANSI escape sequences doesn't do the trick neither.


Solution

  • import sys
    
    _lastlen = 0
    def overwrite(s):
        global _lastlen
        sys.stdout.write("\r" + s + " "*(_lastlen - len(s)))
        sys.stdout.flush()
        _lastlen = len(s)
    
    overwrite("aaaa")
    overwrite("bb")