import time
import sys
sys.stdout.write(\"1\")
time.sleep(5)
print(\"2\")
will print \"12\" after 5 seconds
import time
import sys
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()
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.
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.
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?
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.
Because stdout
is buffered. You may be able to force the output sooner with a sys.stdout.flush()
call.