原代码出处:https://www.cnblogs.com/lustralisk/p/pythonProgressBar.html
在上面这篇文章里其实作者把很多细节讲得挺清楚的,我在这里只是结合我最后的理解把代码做一下注释,
import time,sys
class ProgressBar:
def __init__(self, count = 0, total = 0, width = 50):
self.count = count #当前的进度数,或者可以理解为已完成的迭代数量
self.total = total #总的迭代数量
self.width = width #进度条的长度
def move(self):
self.count += 1 #使进度条前进
def log(self, s):
sys.stdout.write(' ' * (self.width + 9) + '\r') #在上一次的指针处打印,就相当于清除最后一次输出,\r指的是将指针移动到开始处
sys.stdout.flush() #将缓冲区刷到控制台上
print(s)
progress = self.width * self.count / self.total #计算当前进度条应该占的位置大小
sys.stdout.write('{0:3}/{1:3}: '.format(self.count, self.total)) #输出迭代比,就是数字上的进度
sys.stdout.write('#' * int(progress) + '-' * (self.width - int(progress)) + '\r') #输出进度条上的输出
if progress == self.width:
sys.stdout.write('\n')#如果进度条走完了,就输出换行,表示当前行不能再被修改,或者说移动指针的位置,指针的位置是修改的关键
sys.stdout.flush() #输出到控制台
bar = ProgressBar(total = 10)
for i in range(10):
bar.move()
bar.log('We have arrived at: ' + str(i + 1))
time.sleep(1)
总的思路就是利用1)sys.stdout.write是写到指针所指向的地方,结合2)”\r”能使指针又回到当前起始处,去造成修改了进度条的错觉,其实那一行都被修改了;然后里面有个可能会有点迷惑的是“self.width+9”,仔细观察我们进度条的输出,你会发现除了进度条还有9个字符,目的是覆盖上一次的输出。
这个实现比较简单,也方便再定制,只要你清楚原理就行了。