Reputation: 2703
How to override print function in Python 2.2 in order to being able to redirect output to custom logger.
Upvotes: 0
Views: 162
Reputation: 532153
I don't have a version of 2.2 to check (why are you using such an old version?), but I suspect the following is valid for all 2.x.
The print
statement recognizes a first argument beginning with >>
to indicate which file to write to.
The following are identical:
print "foo", "bar"
print >>sys.stdout, "foo", "bar"
As such, you can specify any file
object as the target file.
f = open("log.txt", "w")
print >>f, "foo", "bar"
If you want to redirect every print
statement (or at least all the ones that aren't using a specific file as shown above), you can simply replace sys.stdout
with your desired file.
sys.stdout = open("log.txt", "w")
print "foo", "bar" # Goes to log.txt
If you need it, the original standard output is still available via sys.__stdout__
.
Upvotes: 1