5

Some programs are able to amend console output, wget easily comes to mind.

enter image description here

How can I do that in pure Python? I know IPython has clear_output(). I tried that but even that does not work. And I would prefer pure Python.

from IPython.core.display import clear_output
from time import sleep

for i in range(100):
    clear_output()
    print '[', '='*i, ' '*(100-i), ']'
    sleep(0.1)

asciicast

ArekBulski
  • 1,201

3 Answers3

11

Though a proper library is the best solution, I'd like to show a simple alternative: use \r (carriage return) instead of \n (line feed) for line endings, so that that the cursor is placed at the start of the current line, instead of on the next line.

#! /usr/bin/python3

from time import sleep

for i in range(100):
    print('[' + '='*i + ' '*(100-i) + ']', end='\r')
    sleep(0.1)
muru
  • 207,228
6

Solution hinted by Helio works great! I needed to pip install progressbar first but then one of official examples works like a charm.

from progressbar import *    
pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=300).start()
for i in range(300):
    time.sleep(0.01)
    pbar.update(i+1)
pbar.finish()

Official site (with examples): https://code.google.com/p/python-progressbar/

ArekBulski
  • 1,201
5

There are actually a number of packages that allow you to write a command line interface. I know that click has a progress bar, for instance.

Oh, and regarding your requirement "pure python", that my friend is something that is unpythonic. Python wants you to use third party packages.

asciicast

don.joey
  • 29,392