将命令行变成动态进度条的实现原理
2023-12-09 23:30:54
如何实现一个命令行的进度条
在很多命令行工具中,当执行一个耗时较长的任务时,为了提高用户的体验,通常会显示一个进度条来告诉用户当前任务的进展情况。很多CLI工具为了提高DX,在做耗时长的工作时,都会在命令行显示一个进度条。web端的进度条写多了,命令行的进度条还没写过,所以这里造个简易轮子,了解下原理。
实现原理并不复杂,只需要将进度条的X%部分和(100-X)%部分的字符不同即可。在命令行中,可以通过ANSI转义序列来控制输出文本的颜色和样式。
ANSI转义序列是以一个转义字符(通常是\033)开始的一系列字符,用来控制终端输出的色彩、样式等。例如,以下转义序列可以将文本的颜色设置为红色:
\033[31m
以下转义序列可以将文本的背景色设置为蓝色:
\033[44m
利用这些转义序列,我们可以很容易地实现一个简单的命令行进度条。
import time
def progress_bar(percent):
"""
Prints a progress bar to the console.
Args:
percent: The percentage of the task that has been completed.
"""
# Calculate the number of characters to fill the progress bar.
num_chars = int(percent * 50 / 100)
# Create the progress bar string.
progress_bar_string = "["
# Fill the progress bar with green characters.
for i in range(num_chars):
progress_bar_string += "\033[32m=\033[0m"
# Fill the rest of the progress bar with red characters.
for i in range(50 - num_chars):
progress_bar_string += "\033[31m-\033[0m"
# Add the percentage to the progress bar string.
progress_bar_string += "] {}%".format(percent)
# Print the progress bar to the console.
print(progress_bar_string)
# Test the progress bar.
for i in range(1, 101):
progress_bar(i)
time.sleep(0.1)
这个示例代码首先定义了一个progress_bar()
函数,该函数接收一个参数percent
,表示任务完成的百分比。然后,函数计算出需要填充进度条的字符数,并创建一个进度条字符串。进度条字符串由一个方括号开始,然后是绿色字符表示已完成的部分,接着是红色字符表示未完成的部分,最后是百分比。最后,函数将进度条字符串打印到控制台。
在progress_bar()
函数中,我们使用了ANSI转义序列来控制文本的颜色。当我们想填充进度条的已完成部分时,我们使用以下转义序列将文本的颜色设置为绿色:
\033[32m
当我们想填充进度条的未完成部分时,我们使用以下转义序列将文本的颜色设置为红色:
\033[31m
在每个字符后面,我们都使用了另一个转义序列\033[0m
来将文本的颜色重置为默认值。
运行这个示例代码,你就可以看到一个动态的命令行进度条了。
除了使用ANSI转义序列,我们还可以使用ASCII码来实现命令行进度条。ASCII码是每个字符对应的数字编码,我们可以通过在终端中输出特定的ASCII码来控制文本的颜色和样式。
以下ASCII码可以将文本的颜色设置为红色:
\x1B[31m
以下ASCII码可以将文本的背景色设置为蓝色:
\x1B[44m
我们可以利用这些ASCII码来实现一个简单的命令行进度条。
import time
def progress_bar(percent):
"""
Prints a progress bar to the console.
Args:
percent: The percentage of the task that has been completed.
"""
# Calculate the number of characters to fill the progress bar.
num_chars = int(percent * 50 / 100)
# Create the progress bar string.
progress_bar_string = "["
# Fill the progress bar with green characters.
for i in range(num_chars):
progress_bar_string += "\x1B[32m=\x1B[0m"
# Fill the rest of the progress bar with red characters.
for i in range(50 - num_chars):
progress_bar_string += "\x1B[31m-\x1B[0m"
# Add the percentage to the progress bar string.
progress_bar_string += "] {}%".format(percent)
# Print the progress bar to the console.
print(progress_bar_string)
# Test the progress bar.
for i in range(1, 101):
progress_bar(i)
time.sleep(0.1)
这个示例代码和上一个示例代码类似,只是我们将ANSI转义序列替换成了ASCII码。
运行这个示例代码,你也可以看到一个动态的命令行进度条了。
希望这篇博文能帮助你了解命令行进度条的实现原理。如果您有任何问题或建议,请随时告诉我。