Wednesday, March 25, 2015

Re-printing a line (in Python)

I love those progress bars in the command line. You know, like when you install Linux (or rather when I used to install Linux, nowadays the cool kids have full graphical interface installers).

Something like this:

I always thought you had to use curses or something equally magical to do this. Then I ran into this post. It turns out the character '\r' moves the cursor to the beginning of the line and you can use that, for example in Python, to create an animated progress bar.

def progress_bar(title, f, cols):
  """Draw a nifty progress bar.
  '\r' trick from

  :param title: leading text to print
  :param f:     fraction completed
  :param cols:  how many columns wide should the bar be
  x = int(f * cols + 0.5)
  sys.stdout.write('\r' + title + '[' + '.' * x + ' ' * (cols - x) + ']\r')

(Oh yeah, I use animated .gifs. I'm THAT old)

No comments:

Post a Comment