发布的答案都没有完全满足我的需求。所以我写了我自己的,如上图所示。我需要的功能:
- 只传递步数和总步数,它完成了计算完成百分比的艰巨工作。
- 仅使用 60 个字符空间,将它们分成 240 个“刻度”,以提供从 0.25 % 到 100% 的更精细的显示。
- 支持添加标题。
- 可选百分比在行尾完成。
- 可变长度进度条,默认为 60 个字符或 240 个“记号”。
如何调用进度显示
调用进度显示非常简单。对于上面的示例.gif,该函数是使用以下方法调用的:
percent_complete(step, total_steps, title="Convert Markdown")
在 CSV 格式的 Stack Exchange 数据转储中,len(rows) 的 total_steps 约为 2,500。 step 是当前行号,因为每个 Stack Exchange Markdown Q&A 都转换为 Kramdown(用于 GitHub Pages)。
Python 代码
代码很简单,但比其他答案长一点:
def percent_complete(step, total_steps, bar_width=60, title="", print_perc=True):
import sys
fill = "▒" # Fill up to bar_width
utf_8s = ["▉", "▎", "▌", "▊"] # UTF-8 left blocks: 7/8, 1/4, 1/2, 3/4
perc = 100 * float(step) / float(total_steps)
max_ticks = bar_width * 4
num_ticks = int(round(perc / 100 * max_ticks))
full_ticks = num_ticks / 4 # Number of full blocks
part_ticks = num_ticks % 4 # Size of partial block (array index)
disp = bar = "" # Blank out variables
bar += utf_8s[0] * full_ticks # Add full blocks into Progress Bar
# If part_ticks is zero, then no partial block, else append part char
if part_ticks > 0:
bar += utf_8s[part_ticks]
# Pad Progress Bar with fill character
bar += fill * int((max_ticks/4 - float(num_ticks)/4.0))
if len(title) > 0:
disp = title + ": " # Optional title to progress display
disp += bar # Progress bar to progress display
if print_perc:
# If requested, append percentage complete to progress display
if perc > 100.0:
perc = 100.0 # Fix "100.04 %" rounding error
disp += " {:6.2f}".format(perc) + " %"
# Output to terminal repetitively over the same line using '\r'.
sys.stdout.write("\r" + disp)
sys.stdout.flush()
Python 代码注释
几点:
-
[ .... ] 方括号占位符不是必需的,因为存在用于相同目的的填充字符。这样可以节省两个额外字符以使进度条更宽。
-
bar_width 关键字参数可以根据屏幕宽度使用。 60 的默认值似乎适合大多数用途。
-
print_perc=True 关键字参数默认值可以通过在调用函数时传递print_perc=False 来覆盖。这将允许更长的进度条。
-
title="" 关键字参数默认为无标题。如果您希望使用一次,title="My Title" 和 : 将自动添加到其中。
- 当您的程序完成后,记得调用
sys.stdout.write("\r") 后跟sys.stdout.flush() 以清除进度显示行。
总结
这个答案比其他答案长一点,但重要的是要注意它是一个完整的解决方案,而不是您需要添加更多代码的解决方案的一部分。
另一点是这个解决方案没有依赖项,也没有额外的安装。 Python 支持 UTF-8 字符集,gnome-terminal 不需要额外的设置。如果您使用的是 Python 2.7,则可能需要在 shebang 之后使用# -*- coding: utf-8 -*-。 IE 作为程序的第二行。
该函数可以转换为具有单独 init、update、pause(用于将调试内容打印到屏幕)、resume 和 close 方法的类。
此函数是从 bash 脚本转换而来的。每当电视音量发生变化时,bash 脚本都会以libnotify-bin(弹出气泡消息)显示索尼电视音量。如果您对 bash 版本感兴趣,请在下面发表评论。