实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
当前回答
下面是我使用@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("")
其他回答
你可以使用\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()
在尝试了Mark Rushakoff的解决方案后,我今天看到了这个帖子
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)
我可以说这在使用python 3.4.3 64位的W7-64上工作得很好,但仅限于本机控制台。但是,当使用spyder 3.0.0dev的内置控制台时,换行符仍然/再次出现。由于我花了一些时间来弄清楚,我想在这里报告这一观察结果。
对于Python 3.6,以下工作为我更新输出内联:
for current_epoch in range(10):
for current_step) in range(100):
print("Train epoch %s: Step %s" % (current_epoch, current_step), end="\r")
print()
在这里你可以使用以下代码作为函数:
def drawProgressBar(percent, barLen = 20):
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i < int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
使用.format:
def drawProgressBar(percent, barLen = 20):
# percent float from 0 to 1.
sys.stdout.write("\r")
sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
sys.stdout.flush()
根据上面的答案和其他类似的关于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%