用Python制作一个彩色进度条
时间: 2023-06-01 17:04:11 浏览: 182
以下是使用Python和ANSI转义序列制作彩色进度条的示例代码:
```python
import time
def printProgressBar(iteration, total, prefix='', suffix='', decimals=1, length=50, fill='█', printEnd="\r"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\033[2K\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end=printEnd)
# Print New Line on Complete
if iteration == total:
print()
# Example Usage
if __name__ == '__main__':
items = list(range(0, 57))
l = len(items)
# Initial call to print 0% progress
printProgressBar(0, l, prefix='Progress:', suffix='Complete', length=50)
for i, item in enumerate(items):
# Do stuff...
time.sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix='Progress:', suffix='Complete', length=50)
```
在这个示例中,我们使用了ANSI转义序列来控制终端中的文本属性和颜色。`\033[2K\r`序列用于清除当前行并将光标移到行首,以便我们可以更新进度条的值。我们还使用`\033`序列来设置文本颜色和样式,如`\033[1;31m`表示将文本设置为红色和加粗。
阅读全文