views:

164

answers:

4

My question is whether or not there are situations in which sys.stdout.write() is preferable to print. Such as it having better performance or resulting in code that makes more sense.

+1  A: 

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.

Ignacio Vazquez-Abrams
+1  A: 

"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.

So

print 99

is equivalent to:

import sys
sys.stdout.write(str(99) + '\n')
dogbane
+1 for mentioning the newline character! This is the main difference between `print` and `.write()`, I'd say.
EOL
+9  A: 

print is just a thin wrapper that formats the inputs and calls the write function of a given object. By default this object is sys.stdout but you can pass a file 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. see http://docs.python.org/library/functions.html.

in Python 2.6+, print is still a statement but can be used as a function with from __future__ import print_function

luc
This is exactly the kind of answer I was looking for.
shintoist
I am happy to know that it helps. So don't forget to accept it ;-)
luc
print is still a statement in Python 2.7. It can be turned into a function by using `from __future__ import print_function`, but this was already supported in Python 2.6.
lunaryorn
@lunaryorn : you are right. I am going to correct the answer. Thanks
luc
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
@Michael Mior: True, I've said that "it formats the inputs". Better answser would mention what kind of formatting. Thanks for clarification.
luc
A: 

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 were print statements and these do not appear on a server log, so this is an example of a case where you may need to use sys.stdout.write.

LiamSullivan