我想知道如何用Python创建一个漂亮的控制台计数器,就像在某些C/C++程序中一样。
我有一个做事情的循环,当前的输出是这样的:
Doing thing 0
Doing thing 1
Doing thing 2
...更整洁的做法是只更新最后一行;
X things done.我已经在许多控制台程序中看到了这一点,我想知道我是否会/如何在Python中做到这一点。
发布于 2020-04-26 06:42:50
我前段时间写了这篇文章,真的很开心。请随意使用它。
它需要一个index和total,也可以选择title或bar_length。完成后,用复选标记替换沙漏。
⏳ Calculating: [████░░░░░░░░░░░░░░░░░░░░░] 18.0% done
✅ Calculating: [█████████████████████████] 100.0% done
我提供了一个可以运行来测试它的示例。
import sys
import time
def print_percent_done(index, total, bar_len=50, title='Please wait'):
'''
index is expected to be 0 based index.
0 <= index < total
'''
percent_done = (index+1)/total*100
percent_done = round(percent_done, 1)
done = round(percent_done/(100/bar_len))
togo = bar_len-done
done_str = '█'*int(done)
togo_str = '░'*int(togo)
print(f'\t⏳{title}: [{done_str}{togo_str}] {percent_done}% done', end='\r')
if round(percent_done) == 100:
print('\t✅')
r = 50
for i in range(r):
print_percent_done(i,r)
time.sleep(.02)我也有一个版本的响应进度条取决于终端宽度使用shutil.get_terminal_size(),如果这是感兴趣的。
https://stackoverflow.com/questions/6169217
复制相似问题