Printing to a "log screen" in a multi-module QT app

Dave Brueck dave at pythonapocrypha.com
Thu Feb 28 10:36:15 EST 2002


schneida at seiu.org (Anders Schneiderman) wrote in message news:<54abe19d.0202271213.5e6ef2b0 at posting.google.com>...
> I'm writing an application using QT.  Right now when I want to use the
> equivalent of "print", I call a method called "log" that's defined in
> the main class in my main module:
> 
> def log(self, msg):
>    try:
>       self.logArea.insertline(msg, -1)
>    except:
>       self.logArea.insertline(str(msg), -1)
> 
> To call it in other classes that are in other modules of the app, I
> pass "log" to the new class.  For ex:
> 
> class CodeEditor:
>    def __init__ (self, log, ...)
>        self.log = log
> 
> Is there a cleaner way to do this?  For example, is there a way to
> redefine the "print" command?  Whatever solution I come up with, the
> command to print has to be short;  "self.logObject.log('File
> successfully updated')" is too much of a pain.  Any suggestions?

Well, do you ever really need more than one logger? Most likely no, in
which case you don't really need to pass it to each class, just import
it at the beginning of each module. I usually have a program-wide
logger in one module like this:

logf = open('myapp.log','wt')
def log(*args):
   logf.write(' '.join(['%s' % x for x in args]) + '\n')
   logf.flush()

(yours would be slightly different obviously, but not much) and then
import it in each module like this:

from whatever import log

If you _really_ want to redefine 'print' you can (by setting
sys.stdout and sys.stderr to refer to your own file-like object (just
needs a 'write' method)) but that tends to be both confusing and
annoying so I usually use
the above method instead.

-Dave



More information about the Python-list mailing list