9

I'm doing a progressbar for my uploading script and therefor i want to print a row of multiple '#' but i can't get it to work. When i tell Python to not add newline it does remove it but it doesn't work as expected under functions. Using "print ('#', end='')" in Python 3 or "print '#'," in Python 2 removes it but when executed under a functions it doesn't print anything out until the whole function is finished, it should not wait just like normal print.

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. I really need a fix for this. Please help!

Solution: "sys.stdout.flush()" after each print :)

ggustafsson
  • 501
  • 6
  • 11

4 Answers4

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
  • 18,381
  • 5
  • 58
  • 103
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
  • 8,342
  • 4
  • 24
  • 45
0

You can always use the strip() function.

Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
Jay
  • 94
  • 7
0

I tried your code in the IDLE for 2.5. So I had to use print format as - print '#',

Here is what I get when I execute it - The system prints '#' symbol every second. At the end of the loop I get the prompt back on the IDLE. So it seems to me that it is doing what you expect it to do.

Which version you are specifically using? Sorry I do not have version 3. So I cannot test it there.

Sumod
  • 3,746
  • 9
  • 47
  • 68