我的程序没有更新其输出

时间:2016-08-16 08:58:22

标签: python

我正试图制作一种简单的进度条,当每半秒百分比上升时;输出不断更新。为此,我尝试使用'\ r'参数,但代码只是忽略它并反复打印进度条,直到它达到100%。

以下是代码:

import time
def progressBar(value, endvalue, bar_length=20):
    while value <= endvalue:
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent * bar_length)-1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        print("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))))
        value+=1
        time.sleep(0.5)

progressBar(1, 100)

输出:

Percent: [>                   ] 1%

Percent: [>                   ] 2%

Percent: [>                   ] 3%

Percent: [>                   ] 4%

Percent: [>                   ] 5%

Percent: [>                   ] 6%

Percent: [>                   ] 7%

Percent: [->                  ] 8%

Percent: [->                  ] 9%

Percent: [->                  ] 10%

Percent: [->                  ] 11%

依此类推。

有人可以告诉我这里有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我在 OSX 10.11.6 中安装了python 2.7.10 ,以下代码可能符合您在终端中的要求

import time
import sys
def progressBar(value, endvalue, bar_length=20):
    while value <= endvalue:
        percent = float(value) / endvalue
        arrow = '-' * int(round(percent * bar_length)-1) + '>'
        spaces = ' ' * (bar_length - len(arrow))
        print("\rPercent: [{0}] {1}%".format(arrow + spaces, int(round(percent * 100))))
        sys.stdout.write("\033[F")
        value+=1
        time.sleep(0.5)

progressBar(1, 100)