5

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?
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90

3 Answers3

7
  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('.')
L3viathan
  • 26,748
  • 2
  • 58
  • 81
3

This is because print is considered to be an expensive operation: it will usually wait until it has to print a lot of data, or until a new line is encountered (usually only if output is written to a terminal):

Output buffering is determined by file. Use file.flush() to ensure, for instance, immediate appearance on a screen.

Evidently it is not expensive in the sense that it takes minutes: but asking the terminal operator to print new content, or the operating system to write data to a file (in case of I/O redirection) is still not "lightning fast".

You can force to print all data that is still in the queue, by using a flush on the standard output channel.

Community
  • 1
  • 1
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • @Shadowfax: the new line is usually a policy used for terminals: since after a new line is printed, you sometimes ask a user a question. – Willem Van Onsem Mar 03 '16 at 16:50
2

use

 print('.', end="", flush=True)
dede
  • 706
  • 9
  • 19