展示效果
上代码
import time
import sys
def display_progress(total_count, completed_count, start_time, bar_length=50):
"""
显示进度信息的函数,具有固定长度的进度条。
:param total_count: 总数量
:param completed_count: 已完成数量
:param start_time: 开始执行时间
:param bar_length: 进度条的长度(默认为50)
"""
# 计算已完成的百分比
percent_complete = completed_count / total_count
# 计算进度条上显示的#的数量
hash_count = int(round(percent_complete * bar_length))
# 计算已经过去的时间
elapsed_time = time.time() - start_time
# 如果已完成任务大于0,计算预计剩余时间
if completed_count > 0:
total_estimated_time = elapsed_time / percent_complete
remaining_time = total_estimated_time - elapsed_time
else:
remaining_time = 0 # 如果没有完成任何任务,剩余时间未知
# 清除当前行
sys.stdout.write('\r')
# 打印进度条、完成情况、执行时间和预计剩余时间
sys.stdout.write(f"进度: [{'#' * hash_count}{'-' * (bar_length - hash_count)}] "
f"{percent_complete * 100:.2f}% 完成 "
f"({completed_count}/{total_count}) "
f"执行时间: {elapsed_time:.2f}秒 "
f"预计剩余时间: {remaining_time:.2f}秒")
sys.stdout.flush()
# 使用示例
total_count = 10000
start_time = time.time()
for i in range(total_count):
time.sleep(0.001) # 模拟任务执行时间
display_progress(total_count, i + 1, start_time)
sys.stdout.write('\n')
代码解释:
display_progress
函数定义了一个用于显示进度信息的函数,包括一个固定长度的进度条。- 参数说明:
total_count
:总数量completed_count
:已完成数量start_time
:开始执行时间bar_length
:进度条的长度,默认为50
- 函数内部逻辑:
- 计算已完成的百分比。
- 根据百分比计算进度条上显示的 ‘#’ 数量。
- 计算已经过去的时间。
- 如果已完成任务数量大于0,计算预计剩余时间;否则,剩余时间设为0。
- 使用
sys.stdout.write
和sys.stdout.flush
在同一行中打印进度条、完成情况、执行时间和预计剩余时间。
- 使用示例:
- 定义
total_count
和start_time
。 - 循环执行任务,每次执行后调用
display_progress
函数更新进度条。 - 最后使用
sys.stdout.write
换行,确保输出信息的完整性。
- 定义
使用该函数的好处:
- 提供了一个简单而有效的方法来显示长时间运行任务的进度,使用户能够清晰地了解任务的完成情况和预计剩余时间。
- 进度条的长度和显示格式可以根据需求进行定制。
- 可以轻松地集成到各种 Python 项目中,提高了代码的可读性和用户体验。
解释代码 由GPT4.0 协助完成
贵有贵的道理 。。。