1

I have the following loop which prints a period after each iteration:

for i in range(3):
    time.sleep(1)
    print('.')

This runs exactly as expected: a period is printed to the terminal on a new line in 1 second increments

.  # after 1 seconds
.  # after 2 seconds
.  # after 3 seconds

I want to change the output to print periods to the same line (so the output is more compact and easier to read). However, I have a problem when I change the code to the following:

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

In this case, the single line of periods only print all at once when the for loop is complete:

...  # all after 3 seconds

Am I doing something wrong here or there a limitation with the python print statement?

1
  • This is because print by default operate on each line, if you want it to generate dynamic content like ., then ... You'll need to use sys.stdout.flush() Commented Nov 16, 2018 at 19:35

2 Answers 2

4

By default, terminal output won't appear until a newline is printed.

You can force partial lines to appear immediately by adding flush=True to the print call.

Sign up to request clarification or add additional context in comments.

1 Comment

And in case of Python 2, sys.stdout.flush()
0

Here, this will help you:

import time

for i in range(3):
    time.sleep(1)
    print(".", end="", flush=True)
print("")

Edit

In case you are using python2, be sure to add

from __future__ import print_function

as the first statement to your script.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.