Skip to main content
 首页 » 编程设计

python之进度条动画在 cygwin 中不显示,在 cmd 中正常

2025年05月04日13unruledboy

所以我临时做了一个进度条。这是一个模拟版本:

import sys, time 
 
def Round(n): 
    return str("{0:.2f}".format(n)) 
 
def updateProgressBar(label, percentage): 
    width = 20 
    done = width * int(percentage)/100 
    sys.stdout.write('\r' + label + '\t[' + done * '*' + (width-done) * ' ' + ']\t' + Round(percentage) + '%') 
 
n = 23 
for i in range(n+1): 
    time.sleep(0.25) 
    updateProgressBar('Testing', 100*float(i)/n) 

从 cmd 运行时它工作得很好,增加 % 并增加条形长度。但是当我通过 cygwin 运行它时,直到条形图达到 100% 时才显示任何内容,此时它完全出现,这违背了这一点。有什么指点吗?

请您参考如下方法:

想通了。添加 sys.stdout.flush() 就可以了。我不完全明白为什么,很想知道是否有人可以解释。