MyTetra Share
Делитесь знаниями!
The difference between sys.stdout.write and print?
Время создания: 16.07.2018 11:27
Текстовые метки: python stdout write print
Раздел: Python

Are there situations in which sys.stdout.write() is preferable to print?

(Examples: better performance; code that makes more sense)

python printing stdout

shareimprove this question

edited Nov 17 '17 at 16:55



asked Jul 16 '10 at 9:53

Johanna Larsson



Which version of Python? 2.x or 3.x? – Mark Byers Jul 16 '10 at 9:54

Honestly I'd like to know for both, although I have no experience with Python 3. Updated the question. – Johanna Larsson Jul 16 '10 at 9:59


@S.Lott : asking for the basic differences between sys.stdout.write() and print (and/or why Python has both) is a perfectly reasonable question and does not need examples. OP did not say the command syntax was confusing. – smci Jan 20 '15 at 22:07

add a comment

8 Answers

active oldest votes

up vote


down vote


print is just a thin wrapper that formats the inputs (space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3


In Python 3.x, print becomes a function, but it is still possible to pass something else than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: There is a little difference between the print function and the print statement (and more generally between a function and a statement) pointed by Bakuriu in comments.

In case of error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The func is not called

shareimprove this answer

edited Feb 13 '17 at 7:43

answered Jul 16 '10 at 10:06




It's also worth noting that print also appends a newline to whatever you write which doesn't happen with sys.stdout.write. – Michael Mior Jul 16 '10 at 11:49

@Michael Mior: True, I've said that "it formats the inputs". Better answser would mention what kind of formatting. Thanks for clarification. – luc Jul 16 '10 at 13:35


Also sys.stdout.write is more universal if you ever need to write dual-version code (e.g. code that works simultaneously with Python 2.x as well as Python 3.x). – andreb Dec 16 '10 at 3:28


@MichaelMior You can suppress the newline that print appends with a trailing comma: print "this",; print "on the same line as this" – drevicko Jun 14 '14 at 15:13


sys.stdout.write() also buffers the input and might not flush the input to the fd immediately. in order to make sure that it behaves like the print function, you should add: sys.stdout.flush() – kerbelp Nov 16 '17 at 7:27

show 3 more comments

up vote


down vote

"print" first converts the object to a string (if it is not already a string). It will also put a space before the object if it is not the start of a line and a newline character at the end.

When using stdout, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character.


print 99

is equivalent to:

import sys

sys.stdout.write(str(99) + '\n')

shareimprove this answer

edited Jul 16 '10 at 10:22

answered Jul 16 '10 at 10:03




+1 for mentioning the newline character! This is the main difference between print and .write(), I'd say. – Eric Lebigot Jul 16 '10 at 14:19


NOTE: print can be made to omit the newline. In Python 2.x, put a comma at the end, and a space character will be output, but no newline. E.g. print 99, In Python 3, print(..., end='') will avoid adding newline (and also avoid adding space, unless you do end=' '. – ToolmakerSteve Dec 19 '13 at 2:36


@EOL How funny is that, that someone named EOL makes a comment about '\n'... It made me laugh. I have no life. Kill me. – Depado Jun 23 '15 at 14:14


that's NOT true, print operation behaves slightly different in signal handlers in python2.X, i.e. print can not be replaced with sys.stdout in example:… – ddzialak Oct 27 '15 at 13:13

add a comment

up vote


down vote

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

After finishing developing a script the other day, I uploaded it to a unix server. All my debug messages used print statements, and these do not appear on a server log.

This is a case where you may need sys.stdout.write instead.

shareimprove this answer

edited Sep 29 '12 at 15:17



answered Jul 16 '10 at 10:59




huh? Are you sure this is a difference between print() and sys.stdout.write(), as opposed to the difference between stdout and stderr? For debugging, you should use the logging module, which prints messages to stderr. – ostrokach Jan 25 '16 at 3:05

Ya. Same is true with using nohup and redirecting to a .out file. – May 9 '16 at 15:36

use of sys.stdout.flush() would help. – suprit chaudhary Jun 2 at 1:57

add a comment

up vote


down vote

Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:

import sys

temp = sys.stdout # store original stdout object for later

sys.stdout = open('log.txt', 'w') # redirect all prints to this log file

print("testing123") # nothing appears at interactive prompt

print("another line") # again nothing appears. it's written to log file instead

sys.stdout.close() # ordinary file object

sys.stdout = temp # restore print commands to interactive prompt

print("back to normal") # this shows up in the interactive prompt

Opening log.txt in a text editor will reveal the following:


another line

shareimprove this answer

edited Jun 18 '16 at 5:54



answered Aug 29 '12 at 16:43

Will Townes


Is there any way so that I can print to screen as well as write to the file? – Devesh Saini May 12 '14 at 4:15


@DeveshSaini: Yes, just overwrite sys.stdout with a proxy class that has at least a write() and flush() function. I wrote an example snippet here. – ponycat May 21 '14 at 9:08

add a comment

up vote


down vote

My question is whether or not there are situations in which sys.stdout.write() is preferable to print

If you're writing a command line application that can write to both files and stdout then it is handy. You can do things like:

def myfunc(outfile=None):

if outfile is None:

out = sys.stdout


out = open(outfile, 'w')


# do some stuff

out.write(mytext + '\n')

# ...


if outfile is not None:


It does mean you can't use the with open(outfile, 'w') as out: pattern, but sometimes it is worth it.

shareimprove this answer

edited Jul 7 '13 at 22:00

answered Jul 7 '13 at 20:40

Hamish Downer


add a comment

up vote


down vote

There's at least one situation in which you want sys.stdout instead of print.

When you want to overwrite a line without going to the next line, for instance while drawing a progress bar or a status message, you need to loop over something like

Note carriage return-> "\rMy Status Message: %s" % progress

And since print adds a newline, you are better off using sys.stdout.

shareimprove this answer

answered Aug 31 '16 at 15:24



add a comment

up vote


down vote

In 2.x, the print statement preprocesses what you give it, turning it into strings along the way, handling separators and newlines, and allowing redirection to a file. 3.x turns it into a function, but it still has the same responsibilities.

sys.stdout is a file or file-like that has methods for writing to it which take strings or something along that line.

shareimprove this answer

answered Jul 16 '10 at 9:59

Ignacio Vazquez-Abrams


add a comment

up vote


down vote

Are there situations in which sys.stdout.write() is preferable to print?

For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.

import sys

def printstars(count):

if count >= 1:

i = 1

while (i <= count):




x = x+1




Так же в этом разделе:
MyTetra Share v.0.53
Яндекс индекс цитирования