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

1
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

1
  • Thanks for pointing that out. Click seems to be an amazing framework and I like it. – ArekBulski Apr 12 '15 at 20:27
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)
8
  • It does for me. – muru Apr 12 '15 at 19:37
  • @Helio "A line by percent done" - what does that mean? – muru Apr 12 '15 at 19:43
  • 1
    @muru: asciinema.org/a/18657 – 0x2b3bfa0 Apr 12 '15 at 19:54
  • 1
    @Helio Yeah, that's caused by your terminal not being wide enough for 100+ characters. – muru Apr 12 '15 at 19:55
  • 2
    line ending characters are different for files, this use of \r and \n works on Windows and OSX just fine – UncleZeiv Apr 13 '15 at 0:49
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/

1
  • I'm happy to help (I don't helped so much, but...). – 0x2b3bfa0 Apr 12 '15 at 18:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.