简体   繁体   中英

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.)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM