我想知道如何用Python创建一个漂亮的控制台计数器,就像在某些C/C++程序中一样。
我有一个做事情的循环,当前的输出是这样的:
Doing thing 0
Doing thing 1
Doing thing 2
...更整洁的做法是只更新最后一行;
X things done.我已经在许多控制台程序中看到了这一点,我想知道我是否会/如何在Python中做到这一点。
发布于 2011-05-30 01:34:42
一个简单的解决方案是在字符串之前编写"\r",并且不添加换行符;如果字符串永远不会变短,这就足够了……
sys.stdout.write("\rDoing thing %i" % i)
sys.stdout.flush()稍微复杂一点的是进度条...这是我正在使用的东西:
def startProgress(title):
global progress_x
sys.stdout.write(title + ": [" + "-"*40 + "]" + chr(8)*41)
sys.stdout.flush()
progress_x = 0
def progress(x):
global progress_x
x = int(x * 40 // 100)
sys.stdout.write("#" * (x - progress_x))
sys.stdout.flush()
progress_x = x
def endProgress():
sys.stdout.write("#" * (40 - progress_x) + "]\n")
sys.stdout.flush()您调用startProgress来传递操作的描述,然后调用progress(x),其中x是百分比,最后调用endProgress()
发布于 2016-06-04 20:46:06
更优雅的解决方案可能是:
def progressBar(current, total, barLength = 20):
percent = float(current) * 100 / total
arrow = '-' * int(percent/100 * barLength - 1) + '>'
spaces = ' ' * (barLength - len(arrow))
print('Progress: [%s%s] %d %%' % (arrow, spaces, percent), end='\r')使用value和endvalue调用此函数,结果应为
Progress: [-------------> ] 69 %注:Python2.x版本here。
发布于 2018-07-14 21:35:21
在python 3中,您可以执行以下操作以在同一行上打印:
print('', end='\r')
对于跟踪最新的更新和进度特别有用。
如果你想看看循环的进度,我也推荐tqdm from here。它将当前迭代和总迭代打印为进度条,并显示预期的完成时间。超级有用和快速。适用于python2和python3。
https://stackoverflow.com/questions/6169217
复制相似问题