2

Is there a way to create things like progress bars or updating percentages to the command line in python? It would be much preferred to a new line for every update.

something that looks like this enter image description here

for n in range(10):
    print n*10,'%'
kilojoules
  • 7,600
  • 17
  • 63
  • 123
  • 3
    A simple search on SO reveals a lot of possibilities: [Dynamic terminal printing with python](http://stackoverflow.com/questions/2122385/dynamic-terminal-printing-with-python), [output to the same line overwriting previous output ? python (2.5)](http://stackoverflow.com/questions/4897359/output-to-the-same-line-overwriting-previous-output-python-2-5), etc – davedwards Jul 22 '16 at 01:48
  • 1
    Look at [curses](https://docs.python.org/3/howto/curses.html). – Paul Rooney Jul 22 '16 at 01:49
  • https://gist.github.com/vladignatyev/06860ec2040cb497f0f3 – l'L'l Jul 22 '16 at 02:05
  • Thanks. "Updating text" hadn't yielded anything. Hopefully this will help others who describe this that way. – kilojoules Aug 09 '16 at 00:39

1 Answers1

1

Printing the \r character (carriage return) will move the cursor to the beginning of the line then you can re-write it from there. You will also need to keep the print function from adding a line break by providing end='' as a parameter.

To clarify how to use it, the example below increments a progress counter every second, re-writing the line every second:

import time

a = 0
while 1:
  text = "progress: " + str(a) + "%"
  print ("\r" + text + "        ", end='')
  time.sleep (1)
  a = a + 1

You will need this little amount of empty spaces at the end of the string (after text in the example). When you print variable-length text (like filenames or paths) you may have a situation where the next line update will be shorter than the previous, and you will need to clean up the excess characters from the previous iteration.

Paulo Amaral
  • 551
  • 4
  • 22