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.
I would assume it's due to buffering. Try adding flush=True
as one of the optional parameter to print
.
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 (ie send it to be printed).
from time import sleep
hash = '#'
while True:
print('\r' + hash, end='', flush=True)
hash = hash + '#'
sleep(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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.