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