[colug-432] Code check

Eric Floehr eric at intellovations.com
Sat Aug 3 10:24:24 EDT 2013


> I have this snippet of borrowed code.
>
> def showPayload(msg):
>     payload = msg.get_payload()
>
>     if msg.is_multipart():
>         div = ''
>         for subMsg in payload:
>             print div
>             showPayload(subMsg)
>             div = '------------------------------'
>     else:
>         print msg.get_content_type()
>         print payload[:200]
>


Jim was definitely on the right track with the "file-like object" idea, but
instead of crafting one yourself, as Jim did with Buffer, there is a
built-in string file-like object called StringIO.

So right now you are using the "print" statement which is a convenience
keyword (removed in Python 3) to the built-in print function[1], which
passes in sys.stdout, which is a built-in file-like object to standard out.
So your last line:

print payload[:200]

is equivalent to:

import sys
sys.stdout.writeline(payload[:200] + '\n')

Because of the recursive nature of the showPayload function, you can't
create the file-like object within the function (just like sys.stdout isn't
created within the function). So you will need to pass in the file like
object, and if you want to maintain existing behavior, default to
sys.stdout.  So your function signature becomes:

def showPayload(msg, outfile=sys.stdout)

And then your print statements become 'outfile.write()' calls, so the
entire method looks like:


import sys

def showPayload(msg, outfile=sys.stdout):
    payload = msg.get_payload()

    if msg.is_multipart():
        div = ''
        for subMsg in payload:
            outfile.write(div + '\n')
            showPayload(subMsg, outfile)
            div = '------------------------------'
    else:
        outfile.write(msg.get_content_type() + '\n')
        outfile.write(payload[:200] + '\n')


So now you can use it the same way as you do now (i.e. showPayload(msg))
which will print to standard out, or you can pass in a file like object,
like a file on disk, or a string file, like:

from StringIO import StringIO

stringfile = StringIO()

showPayload(msg, stringfile)

stringfile.getvalue() # Contents of string


Or a regular file:

diskfile = open('/tmp/myfile.txt', 'w')
showPayload(msg, diskfile)
diskfile.close()


[1] http://docs.python.org/2/library/functions.html#print  -- One note,
"print" is an area that is changing a bit between Python 2 and Python 3.
Don't get into the bad habit of using, say, the chevron version of print to
redirect, as it's going away. In Python 3 you'll use this print function
built-in instead.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.colug.net/pipermail/colug-432/attachments/20130803/b61195ff/attachment.html 


More information about the colug-432 mailing list