Question :
Are there situations in which sys.stdout.write()
is preferable to print
?
(Examples: better performance; code that makes more sense)
Answer #1:
print
is just a thin wrapper that formats the inputs (modifiable, but by default with a 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
See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement
In Python 3.x, print
becomes a function, but it is still possible to pass something other than sys.stdout
thanks to the file
argument.
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))
See https://docs.python.org/3/library/functions.html#print
In Python 2.6+, print
is still a statement, but it can be used as a function with
from __future__ import print_function
Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).
In case of an 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 function is not called
Answer #2:
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')
Answer #3:
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:
testing123
another line
Answer #4:
My question is whether or not there
are situations in which
sys.stdout.write()
is preferable to
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.
Answer #5:
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
.
Answer #6:
My question is whether or not there are situations in which
sys.stdout.write()
is preferable to
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
else:
out = open(outfile, 'w')
try:
# do some stuff
out.write(mytext + 'n')
# ...
finally:
if outfile is not None:
out.close()
It does mean you can’t use the with open(outfile, 'w') as out:
pattern, but sometimes it is worth it.
Answer #7:
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.
Answer #8:
A difference between print
and sys.stdout.write
to point out in Python 3, is also the value which is returned when executed in the terminal. In Python 3, sys.stdout.write
returns the length of the string whereas print
returns just None
.
So for example running following code interactively in the terminal would print out the string followed by its length, since the length is returned and output when run interactively:
>>> sys.stdout.write(" hi ")
hi 4