python 命令行进度条
实现简单的命令行进度条功能, 同时可以在进度条前后显示信息
github:https://github.com/Att100/ProgressBar-python
PS:如需要更改进度条的长度, 请将代码中"[%3s%%]: [%-20s]"中的20改成其他长度, 比如40, 50, 同时也需要修改self.barLength的值为相同数值。
代码
- ProgressBar.py
import math
class ProgressBar:
def __init__(self, maxStep=150, fill="#"):
self.maxStep = maxStep
self.fill = fill
self.barLength = 20
self.barInterval = 0
self.prInterval = 0
self.count = 0
self.progress = 0
self.barlenSmaller = True
self.genBarCfg()
def genBarCfg(self):
if self.maxStep >= self.barLength:
self.barInterval = math.ceil(self.maxStep / self.barLength)
else:
self.barlenSmaller = False
self.barInterval = math.floor(self.barLength / self.maxStep)
self.prInterval = 100 / self.maxStep
def resetBar(self):
self.count = 0
self.progress = 0
def updateBar(self, step, headData={}, endData={}, keep=False):
head_str = "\r"
end_str = " "
process = ""
if self.barlenSmaller:
if step != 0 and step % self.barInterval == 0:
self.count += 1
else:
self.count += self.barInterval
self.progress += self.prInterval
for key in headData.keys():
head_str = head_str + key + ": " + str(headData[key]) + " "
for key in endData.keys():
end_str = end_str + key + ": " + str(endData[key]) + " "
if step == self.maxStep:
process += head_str
process += "[%3s%%]: [%-20s]" % (100.0, self.fill * self.barLength)
process += end_str
if not keep:
process += "\n"
else:
process += head_str
process += "[%3s%%]: [%-20s]" % (round(self.progress, 1), self.fill * self.count)
process += end_str
print(process, end='', flush=True)
- demo.py
from ProgressBar import *
import time
if __name__ == "__main__":
# basic using
bar = ProgressBar(maxStep=100)
for i in range(1, 101):
time.sleep(0.1)
bar.updateBar(i)
# using of resetBar() and data display
outside=5
inside=100
bar = ProgressBar(maxStep=inside)
for i in range(1, outside+1):
for j in range(1, inside+1):
time.sleep(0.06)
bar.updateBar(j, headData={'out':i}, endData={'in':j})
bar.resetBar() # restBar()
# set filled string
bar = ProgressBar(maxStep=100, fill='=')
for i in range(1, 101):
time.sleep(0.1)
bar.updateBar(i)
# parameter 'keep' in updateBar()
bar = ProgressBar(maxStep=100, fill='=')
for i in range(1, 101):
time.sleep(0.1)
bar.updateBar(i, keep=True)
bar.updateBar(i, headData={'keep':''}, keep=True)
time.sleep(1)
bar.updateBar(i, headData={'is':''}, keep=True)
time.sleep(1)
bar.updateBar(i, headData={'True':''})
time.sleep(2)
运行demo.py的效果
[100.0%]: [###################]
out: 1 [100.0%]: [####################] in: 100
out: 2 [100.0%]: [####################] in: 100
out: 3 [100.0%]: [####################] in: 100
out: 4 [100.0%]: [####################] in: 100
out: 5 [100.0%]: [####################] in: 100
[100.0%]: [====================]
True: [100.0%]: [====================]