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__

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.



No comments yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: