views:

1723

answers:

6

Am i able to overload the print function? and call the normal function? What i want to do is after a specific line i want print to call my print which will call the normal print and write a copy to file.

Also i dont know how to overload print. I dont know how to do variable length arguments. i'll look it up soon but http://stackoverflow.com/questions/550470/overload-print-python/550477#550477 just told me i cant overload print in 2.x which is what i am using.

+2  A: 

In Python 2.x you can't, because print isn't a function, it's a statement. In Python 3 print is a function, so I suppose it could be overridden (haven't tried it, though).

Joonas Pulakka
+3  A: 

I don't think you can overload print, but Python has a robust logging package that is highly customizable.

http://docs.python.org/library/logging.html

Joe Holloway
+11  A: 

Overloading print is a design feature of python 3.0 to address your lack of ability to do so in python 2.x.

However, you can override sys.stdout. (example.) Just assign it to another file-like object that does what you want.

Alternatively, you could just pipe your script through the the unix tee command. python yourscript.py | tee output.txt will print to both stdout and to output.txt, but this will capture all output.

ʞɔıu
+2  A: 

Though you can't replace the print keyword (in Python 2.x print is a keyword), it's common practice to replace sys.stdout to do something similar to print overriding; for example, with an instance of StringIO.StringIO. This will capture all of the printed data in the StringIO instance, after which you can manipulate it.

cdleary
+1  A: 

I came across the same problem.

How about this:

class writer :
    def __init__(self, *writers) :
     self.writers = writers

    def write(self, text) :
     for w in self.writers :
      w.write(text)

import sys

saved = sys.stdout
fout = file('out.log', 'w')
sys.stdout = writer(sys.stdout, fout)
print "There you go."
sys.stdout = saved
fout.close()

It worked like a charm for me. It was taken from http://mail.python.org/pipermail/python-list/2003-February/188788.html

+1  A: 

I answered the same question on a different SO question

Essentially, simplest solution is to just redirect the output to stderr as follows, in the wsgi config file.

sys.stdout = sys.stderr
Lakshman Prasad