print(foo, end="") not working in terminal

Question:

So this is some code that is supposed to print text, similar to how Pokemon does. Purely for fun.

The problem is that print(x, end="") does not work when the program is run in the terminal, but it works fine when run using IDLE.

import time

lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."

for x in lorem:
    print(x, end="")
    time.sleep(0.03)

For some reason the program works fine if I put a print statement before print(x, end="").

for x in lorem:
    print()
    print(x, end="")
    time.sleep(0.03)

Does anyone have any idea what is causing this? And maybe how to fix it?

Asked By: Daniel

||

Answers:

This is happening because python uses a buffer to write to stdout. in order to get the desired effect, you must put sys.stdout.flush() at the end of your code…

import time, sys

lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit."

for x in lorem:
    print(x, end="")
    time.sleep(0.03)
    sys.stdout.flush()

This will print out each character individually at the rate of 1 character per 0.03 seconds

Answered By: jalomas7
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.