Python 简单增量进度条代码示例
这是一个简单的增量进度条的 Python 代码:
import time
def progress_bar(total):
bar_length = 50
for i in range(total):
percent = i / (total - 1)
hashes = '#' * int(percent * bar_length)
spaces = ' ' * (bar_length - len(hashes))
print('
Progress: [' + hashes + spaces + '] ' + str(int(percent * 100)) + '%', end='', flush=True)
time.sleep(0.1)
if __name__ == '__main__':
progress_bar(20)
这个进度条会在每次循环中自动增加,直到达到总数。进度条的长度是 50,每次循环会计算当前的完成百分比,并根据百分比计算出当前进度条的长度。最后输出进度条和百分比。每次输出进度条时,需要使用 '\r' 将光标移动到行首,这样可以避免多行输出。最后使用 'end=''' 和 'flush=True' 可以将输出立即刷新到屏幕上。
原文地址: https://www.cveoy.top/t/topic/lDVk 著作权归作者所有。请勿转载和采集!