Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do python print statements that contain 'end=' arguments behave differently in while-loops?

I'm running python version 2.7.3 on MacOSX.

Consider this block of code:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x)
    x += 1
    time.sleep(1)

If I run this script, I observe the output I expect: The numbers 0 through 4 with a \n character appended to each number. Futhermore, each number displays after a one second pause.

0
1
2
3
4

Now consider this code block:

from __future__ import print_function
import time
x = 0
while x < 5:
    print(x, end='')
    x += 1
    time.sleep(1)

The output is what I expect, 01234 without the \n's, but the timing is unexpected. Rather than displaying each digit after a one-second pause, the process waits four seconds, then displays all five numbers.

Why does print('string') behave differently from print('string', end='') in while-loops? Is there any way to display the characters without newlines, one second at a time? I tried sys.stdout.write(str(x)), but it behaves the same way as print(end='').

like image 302
Christopher Avatar asked Dec 26 '12 23:12

Christopher


People also ask

How do you print on the same line in a for loop in Python?

Modify print() method to print on the same line The print method takes an extra parameter end=” “ to keep the pointer on the same line. The end parameter can take certain values such as a space or some sign in the double quotes to separate the elements printed in the same line.

What does the print function do in Python?

Definition and Usage. The print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


2 Answers

Because the output stream is line-buffered - since it's not explicitly being flushed in between print statements, it waits until it sees a newline to flush the output.

You can force flushing via sys.stdout.flush().

Alternatively if you run Python with the -u flag, it will disable line buffering.

like image 95
Amber Avatar answered Nov 15 '22 08:11

Amber


This is just python buffering stdout. This answer has some more info.

You can flush it like this:

import sys
from __future__ import print_function
import time
x = 0
while x < 5:
    print(x, end='')
    x += 1
    sys.stdout.flush()
    time.sleep(1)

Alternatively start python python -u and it won't be buffered.

like image 22
Andrew Barrett Avatar answered Nov 15 '22 07:11

Andrew Barrett