//
you're reading...
Python, Source Code

Python – Redirect Stdout

There are two ways to redirect the Stdout to a file.

The first technique is based on redirecting sys.sysout by assigning a writable object (such as a file object) to it. The print statements that follow will write to that object, instead of the default standard output. The drawback is that you should remember to reset sys.sysout to sys.__stdout__ if you want your default standard output back.

import sys
fileHandle = open('c:/out.log', 'w')
sys.stdout = fileHandle
print 'This message will be logged instead of displayed'
sys.stdout = sys.__stdout__
fileHandle.close()

The second technique came to my attention when I reread python. It involves redirecting the print statement directly as follows:

print >> output, "hello world"

Both these techniques have proved to be very handy while logging.

Discussion

No comments yet.

Leave a comment