给我用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('\rProgress: [{0}] {1}%'.format(hashes + spaces, 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/rXG 著作权归作者所有。请勿转载和采集!