首页 > 解决方案 > 如何在python3.7中固定的某个地方打印任务的进度

问题描述

我正在尝试运行一个耗时的“for”循环,并希望在控制台的固定位置打印该过程并刷新每个循环

我尝试这样的打印功能

for i in range(total):
    ...some code....
    print('---%.2f---'%(float(i)/total), sep='')

好像不行

标签: python-3.x

解决方案


我用这个答案来显示进度条:

使用的方法:

def startProgress(title):
    global progress_x
    sys.stdout.write(title + ": [" + "-"*50 + "]" + chr(8)*51)
    sys.stdout.flush()
    progress_x = 0


def progress(x):
    global progress_x
    x = int(x * 50 // 100)
    sys.stdout.write("#" * (x - progress_x))
    sys.stdout.flush()
    progress_x = x


def endProgress():
    sys.stdout.write("#" * (50 - progress_x) + "]\n")
    sys.stdout.flush()

使用示例:

import time
import sys

startProgress("Test")
for i in range(500):
    progress(i * 100 / 500)
    time.sleep(.1)
endProgress()

#随着进度的同时移动,进度将如下所示:

在此处输入图像描述


推荐阅读