Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 641
Daniel Avatar asked Feb 05 '16 18:02

Daniel


People also ask

How do you end an in print statement?

The end parameter in the print function is used to add any string. At the end of the output of the print statement in python. By default, the print function ends with a newline. Passing the whitespace to the end parameter (end=' ') indicates that the end character has to be identified by whitespace and not a newline.

How do I print Python output in terminal?

Print to Console in Python. To print strings to console or echo some data to console output, use Python inbuilt print() function. print() function can take different type of values as argument(s), like string, integer, float, etc., or object of a class type.

Does Python print flush stdout?

Each stdout. write and print operation will be automatically flushed afterwards.

What is flush Python print?

Pythons print method as an exclusive attribute namely, flush which allows the user to decide if he wants his output to be buffered or not. The default value of this is False meaning the output will be buffered. If you change it to true, the output will be written as a sequence of characters one after the other.


1 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

like image 129
jalomas7 Avatar answered Oct 27 '22 18:10

jalomas7