温馨提示×

python进度条代码如何写

小亿
96
2024-01-26 15:29:28
栏目: 编程语言

以下是一个基本的Python进度条代码示例:

import time

def progress_bar(total, current, length=50):
    percent = current/total
    arrow = '#' * int(length * percent)
    spaces = ' ' * (length - len(arrow))
    print(f'[{arrow}{spaces}] {int(percent*100)}%', end='\r')

# 示例用法
total = 100
for i in range(total+1):
    progress_bar(total, i)
    time.sleep(0.1)

这个例子中,progress_bar函数接受三个参数:total表示总数,current表示当前进度,length表示进度条的长度,默认为50。此函数根据当前进度计算百分比,并根据百分比生成相应长度的进度条。然后使用\r实现在同一行上覆盖输出,使进度条动态更新。

在示例用法中,我们模拟了一个进度从0%到100%的过程,每次更新进度条时等待0.1秒,以便观察效果。

0