3 回答

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超4個(gè)贊
一個(gè)簡單的解決方案就是"\r"
在字符串之前寫入而不添加換行符; 如果字符串永遠(yuǎn)不會(huì)變短,這就足夠了......
sys.stdout.write("\rDoing thing %i" % i)sys.stdout.flush()
進(jìn)度條稍微復(fù)雜一點(diǎn)......這是我正在使用的東西:
def startProgress(title): global progress_x sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41) sys.stdout.flush() progress_x = 0def progress(x): global progress_x x = int(x * 40 // 100) sys.stdout.write("#" * (x - progress_x)) sys.stdout.flush() progress_x = xdef endProgress(): sys.stdout.write("#" * (40 - progress_x) + "]\n") sys.stdout.flush()
您調(diào)用startProgress
傳遞操作的描述,然后progress(x)
在哪里x
是百分比,最后endProgress()

TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超10個(gè)贊
更優(yōu)雅的解決方案可能是:
def progressBar(value, endvalue, bar_length=20): percent = float(value) / endvalue arrow = '-' * int(round(percent * bar_length)-1) + '>' spaces = ' ' * (bar_length - len(arrow)) sys.stdout.write("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100)))) sys.stdout.flush()
用value和endvalue調(diào)用這個(gè)函數(shù),結(jié)果應(yīng)該是
Percent: [-------------> ] 69%

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊
另一個(gè)答案可能更好,但這就是我在做的事情。首先,我創(chuàng)建了一個(gè)名為progress的函數(shù),用于打印退格字符:
def progress(x): out = '%s things done' % x # The output bs = '\b' * 1000 # The backspace print bs, print out,
然后我在主函數(shù)的循環(huán)中調(diào)用它,如下所示:
def main(): for x in range(20): progress(x) return
這當(dāng)然會(huì)抹掉整條線,但是你可以把它搞得一團(tuán)糟去做你想要的。我最終使用這種方法制作了一個(gè)進(jìn)度條。
添加回答
舉報(bào)