Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, why won't something print without a newline?

Tags:

python

posix

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?

like image 782
Property404 Avatar asked May 06 '11 22:05

Property404


People also ask

Can you print in Python without newline?

Printing without a new line is simple in Python 3. In order to print without newline in Python, you need to add an extra argument to your print function that will tell the program that you don't want your next string to be on a new line. Here's an example: print("Hello there!", end = '') print("It is a great day.")

Does Python print include New line?

In Python, the built-in print function is used to print content to the standard output, which is usually the console. By default, the print function adds a newline character at the end of the printed content, so the next output by the program occurs on the next line.


2 Answers

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()
like image 125
tmg Avatar answered Sep 26 '22 07:09

tmg


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

like image 24
martineau Avatar answered Sep 25 '22 07:09

martineau