Tim said:
Can anyone suggest a way of capturing the output from smtplib's
set_debuglevel into a list or dictionary (or anything else I can work
with),
Looking at smtplib.py, all of the debug messages go to
the module variable 'stderr', which is a reference to sys.stderr.
That means you can replace smtplib.stderr with something
of your own. Try this untested bit of code
import cStringIO
old_error = smtplib.error
new_error = cStringIO.StringIO()
try:
smtplib.error = new_error
... do your smtplib call here ...
finally:
smtplib.error = old_error
print "Debug messages"
print new_error.getvalue()
What this does is replace smtplib.error with a StringIO,
which is a file-like object that stays in memory. I used
the try/finally to ensure that the original error output
file is restored after the smtplib call ends.
There are other things you could do by making your own
sufficiently file-like object instead of using StringIO.
All it needs to do is implement the 'write' method.
But it may have to accumulate several writes before it
gets a full line.
class ShowWrites:
def write(self, text):
print "Got", repr(text)
To test it out, change my first example so it uses
ShowWrite instead of StringIO and get rid of the
last two lines
new_error = ShowWrite()
and get rid of these two lines
old_error = smtplib.error
new_error = ShowWrites()
try:
smtplib.error = new_error
... do your smtplib call here ...
finally:
smtplib.error = old_error
Andrew
(e-mail address removed)