User1291
User1291

Reputation: 8229

Carriage return without line break on windows

So I have this simple statusbar implementation:

def status_update(current, top, label="Progress"):
    workdone = current/top
    print("\r{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100), end="", flush=True)
    if workdone == 1:
        print()

Works as expected on linux.

On Windows (10, in my case), however, \r apparently creates a new line for each output instead of overwriting the preceding.

How do I stop that? (Preferably in a way that does not break linux compatibility.)

Upvotes: 1

Views: 875

Answers (1)

Raghava Dhanya
Raghava Dhanya

Reputation: 967

This might not be best way to do this, but works. Just use \b.

def status_update(current, top, label="Progress"):
    workdone = current/top
    if not hasattr(status_update, "length"):
        status_update.length = 0
    str1="{0:s}: [{1:30s}] {2:.1f}%".format(label,'#' * int(workdone * 30), workdone*100)
    print(('\b'*status_update.length)+str1, end="", flush=True)
    status_update.length=len(str1)
    if workdone == 1:
        print()

here I'm backspacing number of characters printed in last call of status_update

Upvotes: 2

Related Questions