Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange print behavior with time.sleep in python [duplicate]

Tags:

python

sleep

I was trying to create a progress-like thing by printing a dot every second on the same line. Something like "Fishing.....". This is what I used:

import time

print('Fishing', end='')
for i in range(5):
    time.sleep(1)
    print('.', end='')

But it waits for 5 seconds and prints Fishing..... all at once. But when I don't use the end='', it prints dots every second, but on separate lines like so

Fishing.
.
.
.
.

My questions:

  1. Why does print behave this way?
  2. How can I print a dot every second, but on the same line?
like image 770
Sнаđошƒаӽ Avatar asked Jan 06 '23 13:01

Sнаđошƒаӽ


1 Answers

  1. Why does print behave this way?

This has less to do with print and more with your terminal. For performance reasons, the text only gets "flushed" everytime there's a newline character, and not one character at a time.

  1. How can I print a dot every second, but on the same line?

By "flushing" the standard output manually everytime you printed something:

import time
import sys

print('Fishing', end='')
sys.stdout.flush()
for i in range(5):
    time.sleep(1)
    print('.', end='', flush=True)  # another way

If you need this all the time, you could define a seperate flushing print function:

from functools import partial
myprint = partial(print, end='', flush=True)
myprint('Fishing')
for i in range(5):
    time.sleep(1)
    myprint('.')
like image 109
L3viathan Avatar answered Feb 06 '23 16:02

L3viathan