smtplib, capturing output from set_debuglevel ??

Andrew Dalke adalke at mindspring.com
Fri Oct 8 18:34:47 EDT 2004


Tim Williams
> Yeah,  I did wonder about changing the code  (though it's not my first
> choice. I've done it before and caught a crab later),   or could I do it
> with Subclassing?
> 
>  I'm still close to Newbie status, so I can't immediately imagine what  I
> could change the smptblib code to write to,    or  how to subclass to get
> the behaviour I might need.

It can't be done with subclassing.  You'll need to copy smtplib
to a new file.  Call it 'smtplib2.py'.

Edit it so the class constructor takes an output file object

class SMTP:
     ...
     def __init__(self, host = '', port = 0, local_hostname = None,
                  debugfile = sys.stderr):
         ....
         self.debugfile = debugfile

This lets you attach an arbitrary file-like object to each
SMTP instance.

Then go through the class definition and change every place
that looks like

         if self.debuglevel > 0: print>>stderr, 'connect:', (host, port)

into

         self.debugmsg('connect:', (host, port))

and create a new method named 'debugmsg' which looks like

      def debugmsg(self, *args):
         self.debugfile.write(" ".join(map(str, args))) + "\n")

(Or the long way

      def debugmsg(self, *args):
         if args:
           self.debugfile.write(str(args[0]))
           for arg in args[1:]:
             self.debufile.write(" " + str(args[1]))
         self.debugfile.write("\n")

Another option, if you decide to go this route, is that you
can change the protocol and the debug messages.  For example,
if you want it to go to a list you can change this so as
to use a 'debug_msgqueue = []' and so debugmsg appends the
args to that list.

You can also change the actual messages sent by the library.

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list