2017-06-04 30 views
0

換行符回車所以我有這個簡單的狀態欄實現:沒有在Windows

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

按預期工作在Linux上。

然而,在Windows上(10,在我的情況下),\r顯然會爲每個輸出創建一個新行,而不是覆蓋前面的行。

我該如何阻止? (最好以不破壞linux兼容性的方式。)

+0

經典的Windows控制檯的最後一列被寫入時,光標會自動前進到下一行的最後一次通話打印的字符數量。在Windows 10中,這可以通過使用虛擬終端模式來禁用。 – eryksun

回答

1

這可能不是最好的方式來做到這一點,但工作。只需使用\ 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() 

這裏我退格在status_update