Ray Bern
Ray Bern

Reputation: 135

Why does this Python code not print anything

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.

Upvotes: 2

Views: 2209

Answers (2)

Ted Klein Bergman
Ted Klein Bergman

Reputation: 9766

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)

Upvotes: 1

Ngoc N. Tran
Ngoc N. Tran

Reputation: 1068

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

Upvotes: 4

Related Questions