18
import time
import sys
sys.stdout.write("1")
time.sleep(5)
print("2")

will print "12" after 5 seconds

import time
import sys
sys.stdout.write("1\n")
time.sleep(5)
print("2")

will print "1\n" right away, then "2" after 5 seconds

Why is this?

martineau
  • 119,623
  • 25
  • 170
  • 301
Property404
  • 318
  • 4
  • 12

6 Answers6

29

If you add "\n" then stream is flushed automaticaly, and it is not without new line at the end. You can flush output with:

sys.stdout.flush()
tmg
  • 872
  • 6
  • 7
9

Because stdout is buffered. You may be able to force the output sooner with a sys.stdout.flush() call.

martineau
  • 119,623
  • 25
  • 170
  • 301
5

The sys.stdout.write command from the sys module purposefully prints out the statement without the \n character. This is how a normal call to the stdout stream works, such as in C++ or C, where the \n character must be added manually.

However the print command provided by Python automatically adds a \n character to the string, therefore simplifying the code and making it easier to read.

The reason the phenomenon in the first result happens is because the system is waiting for a flush to print out, which is provided by the \n character. You can avoid this by using this command, sys.stdout.flush(), which will flush the stdout stream which forces it to print.

Matt Habel
  • 1,493
  • 2
  • 14
  • 35
4

Buffering. It's not really Python, but rather your operating system/terminal. Output from any program is sent to a buffer, a holding area of memory. When a whole line is collected, it's sent to the screen. There is usually a hook, a method named something like flush(), to force output of partial lines.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186
4

It's because output in Python is buffered by default - ordinarily you won't get the output until the buffer is full or something causes the buffer to be flushed. In this case the \n was sensed and caused an automatic flush.

See this question for ways around the problem: How to flush output of Python print?

Community
  • 1
  • 1
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

Consider that when you type a command into a computer, it doesn't know you're finished until you press ENTER

Similarly, the newline tells Python you've finished that line.

pavium
  • 14,808
  • 4
  • 33
  • 50