Search code examples
pythonwindowscommand-lineoverwritecarriage-return

How can I overwrite/print over the current line in Windows command line?


On Unix, I can either use \r (carriage return) or \b (backspace) to overwrite the current line (print over text already visible) in the shell.

Can I achieve the same effect in a Windows command line from a Python script?

I tried the curses module but it doesn't seem to be available on Windows.


Solution

  • yes:

    import sys
    import time
    
    def restart_line():
        sys.stdout.write('\r')
        sys.stdout.flush()
    
    sys.stdout.write('some data')
    sys.stdout.flush()
    time.sleep(2) # wait 2 seconds...
    restart_line()
    sys.stdout.write('other different data')
    sys.stdout.flush()