【问题标题】:Progress Bar in Python Console on WindowsWindows 上 Python 控制台中的进度条
【发布时间】:2015-11-18 18:44:20
【问题描述】:

除了其他一些链接之外,我还浏览了以下两个链接,并且我已经尝试了提供的大多数示例和建议,但是在我的输出中,进度条没有得到更新,而是显示了新的一个,无论是同一行的末尾还是交替在新线上。我在这里缺少什么,有人可以指导我。

Python Progress Bar

Text Progress Bar in the Console

为方便起见,我正在复制我尝试过的一些代码(来自上述线程的示例)及其输出。我是否理解不正确,它将更新同一行或我缺少什么。感谢你的帮助。我在 Windows 7 上使用 Python 3.4 并在控制台上获取输出(无 GUI)。

示例 1:

import progressbar
import time, sys

progress = progressbar.ProgressBar()
for i in progress(range(80)):
    time.sleep(0.01)

输出 1:

>>> 
  0% |                                                                        |
  1% |                                                                        |
  2% |#                                                                       |
  3% |##                                                                      |
  5% |###                                                                     |
  6% |####                                                                    |
  7% |#####                                                                   |
  8% |######                                                                  |
 10% |#######                                                                 |
 11% |########                                                                |
 12% |#########                                                               |
 13% |#########                                                               |
 15% |##########                                                              |
 16% |###########                                                             |
 17% |############                                                            |
 18% |#############                                                           |
 20% |##############                                                          |
 21% |###############                                                         |
 22% |################                                                        |
 23% |#################                                                       |
 25% |##################                                                      |
 26% |##################                                                      |
 27% |###################                                                     |
 28% |####################                                                    |
 30% |#####################                                                   |
 31% |######################                                                  |
 32% |#######################                                                 |
 33% |########################                                                |
 35% |#########################                                               |
 36% |##########################                                              |
 37% |###########################                                             |
 38% |###########################                                             |
 40% |############################                                            |
 41% |#############################                                           |
 42% |##############################                                          |
 43% |###############################                                         |
 45% |################################                                        |
 46% |#################################                                       |
 47% |##################################                                      |
 48% |###################################                                     |
 50% |####################################                                    |
 51% |####################################                                    |
 52% |#####################################                                   |
 53% |######################################                                  |
 55% |#######################################                                 |
 56% |########################################                                |
 57% |#########################################                               |
 58% |##########################################                              |
 60% |###########################################                             |
 61% |############################################                            |
 62% |#############################################                           |
 63% |#############################################                           |
 65% |##############################################                          |
 66% |###############################################                         |
 67% |################################################                        |
 68% |#################################################                       |
 70% |##################################################                      |
 71% |###################################################                     |
 72% |####################################################                    |
 73% |#####################################################                   |
 75% |######################################################                  |
 76% |######################################################                  |
 77% |#######################################################                 |
 78% |########################################################                |
 80% |#########################################################               |
 81% |##########################################################              |
 82% |###########################################################             |
 83% |############################################################            |
 85% |#############################################################           |
 86% |##############################################################          |
 87% |###############################################################         |
 88% |###############################################################         |
 90% |################################################################        |
 91% |#################################################################       |
 92% |##################################################################      |
 93% |###################################################################     |
 95% |####################################################################    |
 96% |#####################################################################   |
 97% |######################################################################  |
 98% |####################################################################### |
100% |########################################################################|

示例 2:

for i in range(0, 101, 10):
  sys.stdout.write('\r>> You have finished %3d%%\r' % i)
  sys.stdout.flush()
  sys.stdout.flush()
  time.sleep(1)
print

输出 2:

您已完成 0% >> 您已完成 10% >> 您已完成 20% >> 您已完成 30% >> 您已完成 40% >> 您已完成 50% >> 您已完成 60% >> 你已经完成了 70% >> 你已经完成了 80% >> 你已经完成了 90% >> 你已经完成了 100%

示例 3:

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

print("")
print("progress : 0->1")
for i in range(101):
    time.sleep(0.1)
    update_progress(i/100.0)

print("")
print("Test completed")
time.sleep(1)

输出 3:

>>> 

progress : 0->1

Percent: [                    ] 0.0% 
Percent: [                    ] 1.0% 
Percent: [                    ] 2.0% 
Percent: [=                   ] 3.0% 
Percent: [=                   ] 4.0% 
Percent: [=                   ] 5.0% 
Percent: [=                   ] 6.0% 
Percent: [=                   ] 7.000000000000001% 
Percent: [==                  ] 8.0% 
Percent: [==                  ] 9.0% 
Percent: [==                  ] 10.0% 
Percent: [==                  ] 11.0% 
Percent: [==                  ] 12.0% 
Percent: [===                 ] 13.0% 
Percent: [===                 ] 14.000000000000002% 
Percent: [===                 ] 15.0% 
Percent: [===                 ] 16.0% 
Percent: [===                 ] 17.0% 
Percent: [====                ] 18.0% 
Percent: [====                ] 19.0% 
Percent: [====                ] 20.0% 
Percent: [====                ] 21.0% 
Percent: [====                ] 22.0% 
Percent: [=====               ] 23.0% 
Percent: [=====               ] 24.0% 
Percent: [=====               ] 25.0% 
Percent: [=====               ] 26.0% 
Percent: [=====               ] 27.0% 
Percent: [======              ] 28.000000000000004% 
Percent: [======              ] 28.999999999999996% 
Percent: [======              ] 30.0% 
Percent: [======              ] 31.0% 
Percent: [======              ] 32.0% 
Percent: [=======             ] 33.0% 
Percent: [=======             ] 34.0% 
Percent: [=======             ] 35.0% 
Percent: [=======             ] 36.0% 
Percent: [=======             ] 37.0% 
Percent: [========            ] 38.0% 
Percent: [========            ] 39.0% 
Percent: [========            ] 40.0% 
Percent: [========            ] 41.0% 
Percent: [========            ] 42.0% 
Percent: [=========           ] 43.0% 
Percent: [=========           ] 44.0% 
Percent: [=========           ] 45.0% 
Percent: [=========           ] 46.0% 
Percent: [=========           ] 47.0% 
Percent: [==========          ] 48.0% 
Percent: [==========          ] 49.0% 
Percent: [==========          ] 50.0% 
Percent: [==========          ] 51.0% 
Percent: [==========          ] 52.0% 
Percent: [===========         ] 53.0% 
Percent: [===========         ] 54.0% 
Percent: [===========         ] 55.00000000000001% 
Percent: [===========         ] 56.00000000000001% 
Percent: [===========         ] 56.99999999999999% 
Percent: [============        ] 57.99999999999999% 
Percent: [============        ] 59.0% 
Percent: [============        ] 60.0% 
Percent: [============        ] 61.0% 
Percent: [============        ] 62.0% 
Percent: [=============       ] 63.0% 
Percent: [=============       ] 64.0% 
Percent: [=============       ] 65.0% 
Percent: [=============       ] 66.0% 
Percent: [=============       ] 67.0% 
Percent: [==============      ] 68.0% 
Percent: [==============      ] 69.0% 
Percent: [==============      ] 70.0% 
Percent: [==============      ] 71.0% 
Percent: [==============      ] 72.0% 
Percent: [===============     ] 73.0% 
Percent: [===============     ] 74.0% 
Percent: [===============     ] 75.0% 
Percent: [===============     ] 76.0% 
Percent: [===============     ] 77.0% 
Percent: [================    ] 78.0% 
Percent: [================    ] 79.0% 
Percent: [================    ] 80.0% 
Percent: [================    ] 81.0% 
Percent: [================    ] 82.0% 
Percent: [=================   ] 83.0% 
Percent: [=================   ] 84.0% 
Percent: [=================   ] 85.0% 
Percent: [=================   ] 86.0% 
Percent: [=================   ] 87.0% 
Percent: [==================  ] 88.0% 
Percent: [==================  ] 89.0% 
Percent: [==================  ] 90.0% 
Percent: [==================  ] 91.0% 
Percent: [==================  ] 92.0% 
Percent: [=================== ] 93.0% 
Percent: [=================== ] 94.0% 
Percent: [=================== ] 95.0% 
Percent: [=================== ] 96.0% 
Percent: [=================== ] 97.0% 
Percent: [====================] 98.0% 
Percent: [====================] 99.0% 
Percent: [====================] 100% Done...


Test completed
>>> 

编辑:您可以看到正在同一行打印,但它是在最后一次打印的末尾附加而不是覆盖,这是所需的效果。谢谢!

【问题讨论】:

  • 我相信所有示例都是 Windows 命令行控制台 cmd.exe 的进度条,而不是 Python 控制台。
  • @martineau 你是对的。我在cmd上试过了,它可以工作。是否有可能在 Python 控制台上获得相同的功能?
  • @wenzul 与我“在同一行”不同,但它是在末尾附加而不是覆盖以获得进度效果。
  • colorama 支持定位 ANSI 转义码。如果一切都失败了,你可以使用它,例如,尝试this random walker cli implementation

标签: python python-3.x progress-bar windows-7-x64


【解决方案1】:

这是我在应用程序中使用的一个类。适用于我的 Windows 7。

检查百分比是否更改为每次迭代都不再重新打印,print() 是繁重的操作

class ProgressBar:
    """
    Create command-line-style ProgressBar
    """
    def __init__(self, total, prefix='', suffix='', length=100, fill='*'):
        """
        Init ProgressBar
        Start position is always 0, end position is total.
        Usage example:
        progress_bar = ProgressBar(l, prefix='Progress:', suffix='Complete', length=50)
        while some():
            progress_bar.iterate(i + 1)
        :param total: Required, total iterations (Int)
        :param prefix: Optional, prefix string (Str)
        :param suffix: Optional, suffix string (Str)
        :param length: Optional, character length of bar (Int)
        :param fill: Optional, bar fill character (Str)
        """
        self.counter = 0
        self.prev_counter = 0
        self.total = total
        self.percent_size = total/100
        self.prefix = prefix
        self.suffix = suffix
        self.length = length
        self.fill = fill

    def iterate(self, iteration):
        """
        Call in a loop to create terminal progress bar
        @param: iteration: Required, current iteration (Int)
        """
        self.prev_counter = int(iteration/self.percent_size)
        filled_length = int((self.prev_counter/100) * self.length)
        bar = self.fill * filled_length + '-' * (self.length - filled_length)
        if self.prev_counter != self.counter:
            print('\r%s |%s| %s%% %s' % (self.prefix, bar, self.prev_counter, self.suffix), end='\r')
        self.counter = self.prev_counter
        # Print New Line on Complete
        if iteration == self.total:
            print()

【讨论】:

    【解决方案2】:
    >>> import time
    >>> for i in range(0, 101, 10):
    ...     print('\rYou have finished %3d%%' % i, end='', flush=True)
    ...     time.sleep(1)
    ... else:
    ...     print()
    ...
    You have finished 100%
    >>>
    

    适用于我在 win32 上使用 Python 3.4.3...

    Idle 无法正确呈现回车。

    查看python print one line same space。 “完成,我的错误是我使用 IDLE”或Implementing a backspace in Python 3.3.2 Shell using Idle

    Idle 更像是一个 Python 文本编辑器,没有真正的控制台...因此您不能同时解释控制符号并正确打印它...

    >>> print("asd\rfgh")
    asdfgh
    

    【讨论】:

    • 谢谢,但它不适用于 Python 控制台。虽然,它正在使用cmd。输出是相同的,附加在最后一次打印的末尾而不是覆盖。 ( 你已经完成了 0% 你已经完成了 10% 你已经完成了 20% 你已经完成了 30% 你已经完成了 40% 你已经完成了 50% 你已经完成了 60% 你已经完成了 70% 你已经完成了 80% 你已经完成了 90 % 你已经完成了 100% )
    • @AbdulQadir:这不是关于覆盖,而是关于事物的显示方式。如果我运行 python -c "print('\r0\r1\r2\r3')",那么它唯一可见的就是我的 Linux 终端中的一个单独的 3。它在 IDLE 中不起作用。如果在 Windows 控制台中运行它会发生什么?
    • 是的,您必须准确地说您指的是哪个控制台。我只是在 Windows 控制台 (cmd.exe) 中划分了交互式 Python 控制台 (python.exe)。
    • @wenzul 你是对的。我的错。我的意思是 Python IDLE 而不是控制台。当我尝试使用 cmd.exe 时,您的代码和其他示例都有效。很抱歉不清楚。如果有任何可能在 IDLE 中得到相同的结果,我将不胜感激。
    • @AbdulQadir 我检查了,对我来说似乎标准输出没有可能性。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-18
    • 1970-01-01
    • 2010-12-10
    • 2013-05-14
    • 2012-10-21
    • 2016-09-24
    • 2021-11-14
    相关资源
    最近更新 更多