3

I have gone through the below two links in addition to some others and I have tried most all examples and suggestions provided, but in my output the progress bar is not getting updated, rather new one shows, either end of same line or alternately on the new line. What am I missing here, can someone please guide me.

Python Progress Bar

Text Progress Bar in the Console

For ease, I am reproducing some of the codes (from examples of above threads) I have tried and their outputs. Did I understand incorrect that it will update the same line or what am I missing. Appreciate your help. I am using Python 3.4 on Windows 7 and getting the output on console (no GUI).

Example 1:

import progressbar
import time, sys

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

Output 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% |########################################################################|

Example 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

Output 2:

You have finished 0% >> You have finished 10% >> You have finished 20% >> You have finished 30% >> You have finished 40% >> You have finished 50% >> You have finished 60% >> You have finished 70% >> You have finished 80% >> You have finished 90% >> You have finished 100%

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

Output 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
>>> 

Edit: You can see that printing on the same line is happening, but it is appending at the end of the last print rather than overwriting which is the desired effect. Thanks!

Community
  • 1
  • 1
Abdul Qadir
  • 439
  • 1
  • 6
  • 12
  • 1
    I believe all the examples where meant to be progress bars for the Windows command-line console `cmd.exe`, not the Python console. – martineau Aug 25 '15 at 07:16
  • possible duplicate of [Print to the same line and not a new line in python](http://stackoverflow.com/questions/3419984/print-to-the-same-line-and-not-a-new-line-in-python) – wenzul Aug 25 '15 at 07:36
  • @martineau you are correct. I tried it on cmd and it works. Any possibility of getting the same functionality on Python console? – Abdul Qadir Aug 25 '15 at 08:00
  • @wenzul not the same as I am getting "on the same line" but it is appending at the end rather than overwriting to get the progress effect. – Abdul Qadir Aug 25 '15 at 08:01
  • `colorama` supports positioning ANSI escape codes. You could use it if all else fails e.g., try [this random walker cli implementation](http://stackoverflow.com/a/22121542/4279) – jfs Aug 25 '15 at 09:09
  • If you are running the code in Python console then copy-paste the code as is with `>>>` and `...` in it. Otherwise it is misleading e.g., I thought that you can't make `'\r'` work in Windows console. – jfs Aug 25 '15 at 09:14
  • The problem is caused by IDLE, not your script. – wenzul Aug 25 '15 at 09:19
  • @J.F.Sebastian i wasn't aware of difference in pasting method. apologies. I meant Python IDLE and not cmd.exe. the examples work well in cmd. i was wondering if there was any possibility within IDLE. thanks once more – Abdul Qadir Aug 25 '15 at 09:40
  • @AbdulQadir: note: [IDLE is a GUI program](https://docs.python.org/3/library/idle.html) but you say "no GUI" in your question. If you are using a GUI then you could start a GUI progress bar. – jfs Aug 25 '15 at 11:27

2 Answers2

1
>>> 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%
>>>

works for me with Python 3.4.3 on win32...

Idle doesn't render carriage returns properly.

Look into python print one line same space. "done, my mistake i was using IDLE" or Implementing a backspace in Python 3.3.2 Shell using Idle.

Idle is more like a Python text editor and no real console... therefore you cannot interpret a control symbol and print it properly at the same time...

>>> print("asd\rfgh")
asdfgh
Community
  • 1
  • 1
wenzul
  • 3,948
  • 2
  • 21
  • 33
  • thanks but it is not working on Python console. Although, it is working on cmd. Output is same, appending at the end of last print not overwriting. ( You have finished 0% You have finished 10% You have finished 20% You have finished 30% You have finished 40% You have finished 50% You have finished 60% You have finished 70% You have finished 80% You have finished 90% You have finished 100% ) – Abdul Qadir Aug 25 '15 at 08:52
  • @AbdulQadir: It is not about overwriting, it is about how the things are displayed. if I run `python -c "print('\r0\r1\r2\r3')"` then the only thing that it is visible is a lone `3` in my Linux terminal. It doesn't work in IDLE. What happens if you run it in Windows console? – jfs Aug 25 '15 at 09:00
  • Yes, you must be accurate which console you mean. I just devide into interactive Python console (python.exe) inside Windows console (cmd.exe). – wenzul Aug 25 '15 at 09:12
  • @wenzul you are correct. my mistake. I mean Python IDLE and not console. When i try using cmd.exe your code and the other examples work. apologies for not being clear. if there is any possibility of getting the same within IDLE i would really appreciate it. – Abdul Qadir Aug 25 '15 at 09:39
  • @AbdulQadir I checked that, for me it seems that there is no possibility on stdout. – wenzul Aug 25 '15 at 09:42
  • @wenzul thanks for your time. sorry for the confusion. – Abdul Qadir Aug 25 '15 at 11:12
0

Here's a class I use in my applications. Works on Windows 7 for me.

Check if percentage changed not to re-print on every iteration, print() is heavy operation

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