10

I'm trying to create a progress bar in the terminal, by repeatedly printing # symbols on the same line.

When i tell Python to not add newlines - using print('#', end='') in Python 3 or print '#', in Python 2 - it prints as desired, but not until the whole function is finished. For example:

import time

i = 0

def status():
    print('#', end='')

while i < 60:
    status()
    time.sleep(1)
    i += 1

This should print '#' every second but it doesn't. It prints them all after 60 seconds. Using just print('#') prints it out every second as expected. How can I fix this?

Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
ggustafsson
  • 603
  • 7
  • 13
  • Why do you try to reinvent wheels? http://pypi.python.org/pypi/fish/ –  Feb 24 '11 at 06:27
  • I use a solution based on [this](http://nadiana.com/animated-terminal-progress-bar-in-python) which is very cool, imo :) – simon Feb 24 '11 at 06:54

3 Answers3

7

You probably need to flush the output buffer after each print invocation. See How to flush output of Python print?

Community
  • 1
  • 1
ide
  • 19,942
  • 5
  • 64
  • 106
1

Python is buffering the output until a newline (or until a certain size), meaning it won't print anything until the buffer gets a newline character \n. This is because printing is really costly in terms of performance, so it's better to fill a small buffer and only print once in a while instead.

If you want it to print immediately, you need to flush it manually. This can be done by setting the flush keyword argument to True.

import time

word = "One letter at a time"

for letter in word:
    print(letter, end='', flush=True)
    time.sleep(0.25)
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
0

You can always use the strip() function.

Jay
  • 94
  • 7