实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
当前回答
def printProgressBar(value,label):
n_bar = 40 #size of progress bar
max = 100
j= value/max
sys.stdout.write('\r')
bar = '█' * int(n_bar * j)
bar = bar + '-' * int(n_bar * (1-j))
sys.stdout.write(f"{label.ljust(10)} | [{bar:{n_bar}s}] {int(100 * j)}% ")
sys.stdout.flush()
电话:
printProgressBar(30,"IP")
知识产权 |[██████████████----------------------------] 30%
其他回答
下面是我使用@Mark-Rushakoff的解决方案制作的一些东西。自适应调整到终端宽度。
from time import sleep
import os
import sys
from math import ceil
l = list(map(int,os.popen('stty size','r').read().split()))
col = l[1]
col = col - 6
for i in range(col):
sys.stdout.write('\r')
getStr = "[%s " % ('='*i)
sys.stdout.write(getStr.ljust(col)+"]"+"%d%%" % (ceil((100/col)*i)))
sys.stdout.flush()
sleep(0.25)
print("")
根据上面的答案和其他类似的关于CLI进度条的问题,我想我得到了一个普遍的答案。请登录https://stackoverflow.com/a/15860757/2254146查看。
下面是这个函数的一个副本,但是为了适合你的风格进行了修改:
import time, sys
# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
barLength = 20 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
text = "\rPercent: [{0}] {1}% {2}".format( "="*block + " "*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
看起来像
百分比:[====================]99.0%
你可以使用\r(回车)。演示:
import sys
total = 10000000
point = total / 100
increment = total / 20
for i in xrange(total):
if(i % (5 * point) == 0):
sys.stdout.write("\r[" + "=" * (i / increment) + " " * ((total - i)/ increment) + "]" + str(i / point) + "%")
sys.stdout.flush()
'\r'字符(回车)将光标重置到行首,并允许您重写该行之前的内容。
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)
我不能100%确定这是否可以在所有系统上完全移植,但它至少可以在Linux和OSX上运行。
要成为纯python并且不进行系统调用:
from time import sleep
for i in range(21):
spaces = " " * (20 - i)
percentage = 5*i
print(f"\r[{'='*i}{spaces}]{percentage}%", flush=True, end="")
sleep(0.25)