Skip to main content

Posts

Showing posts from March, 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 http://stackoverflow.com/questions/15685063/print-a-progress-bar-processing-in-python :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') sys.stdout.flu