The difference between sys.stdout.write and print?
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,
sys.stdout thanks to the
print('Hello', 'World', 2+3, file=open('file.txt', 'w'))
In Python 2.6+,
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 Exceptionprint("something", 1/0, "other") #doesn't print anything. The function is not called
stdout, you need to convert the object to a string yourself (by calling "str", for example) and there is no newline character.
is equivalent to:
import syssys.stdout.write(str(99) + '\n')
Here's some sample code based on the book Learning Python by Mark Lutz that addresses your question:
import systemp = sys.stdout # store original stdout object for latersys.stdout = open('log.txt', 'w') # redirect all prints to this log fileprint("testing123") # nothing appears at interactive promptprint("another line") # again nothing appears. it's written to log file insteadsys.stdout.close() # ordinary file objectsys.stdout = temp # restore print commands to interactive promptprint("back to normal") # this shows up in the interactive prompt
Opening log.txt in a text editor will reveal the following: