如何在python3.7中固定的位置打印任务的进度

时间:2019-05-22 10:43:58

标签: python-3.x

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

我尝试这样的打印功能

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

似乎不起作用

1 个答案:

答案 0 :(得分:0)

我使用此answer显示进度栏:

使用的方法:

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()

进度#会在进度的同时移动:

enter image description here