1

I was wondering, why does this Python code not print anything in my console?

from time import sleep
while True:
    print('#', end='')
    sleep(1)

If I remove the sleep function it works, and if I remove the end='' part it works too. I am using Python 3.9 and I have tested this with Dash, Bash and ZSH. I can achieve the desired output with the following code.

from time import sleep
hash = '#'
while True:
    print('\r' + hash, end='')
    hash = hash + '#'
    sleep(1)

Thank you in advance.

Ray Bern
  • 113
  • 4

2 Answers2

3

I would assume it's due to buffering. Try adding flush=True as one of the optional parameter to print.

kwkt
  • 1,058
  • 3
  • 10
  • 19
  • This worked, thank you. I will mark this as the answer as soon as it lets me do so. – Ray Bern Jan 08 '21 at 08:44
  • IMHO It would be nice if `flush=True` was automatically enabled when `end=...` is specified. (I understand that there is zero chance for such a change). – VPfB Jan 08 '21 at 08:52
  • @VPfB There's multiple ways you can go for that. 1, you can run Python with flag `-u` and it'll go unbuffered. 2, you can change the file descriptor `sys.stdout` to not buffer. Check out https://stackoverflow.com/q/107705/2327379 for more details. – kwkt Jan 08 '21 at 15:01
1

When using print, a newline character is added to your string unless you're overriding it (as you do) with the end parameter. For performance reasons, there exists an I/O buffer that only prints when it encounters a newline or the buffer fills up. Since your string doesn't contain a newline character anymore, you have to manually flush the buffer (i.e. send it to be printed).

from time import sleep
hash = '#'
while True:
    print('\r' + hash, end='', flush=True)
    hash = hash + '#'
    sleep(1)
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50