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?
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
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?
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