PyXR

c:\python24\lib \ email \ Iterators.py



0001 # Copyright (C) 2001-2004 Python Software Foundation
0002 # Author: Barry Warsaw
0003 # Contact: email-sig@python.org
0004 
0005 """Various types of useful iterators and generators."""
0006 
0007 import sys
0008 from cStringIO import StringIO
0009 
0010 
0011 
0012 # This function will become a method of the Message class
0013 def walk(self):
0014     """Walk over the message tree, yielding each subpart.
0015 
0016     The walk is performed in depth-first order.  This method is a
0017     generator.
0018     """
0019     yield self
0020     if self.is_multipart():
0021         for subpart in self.get_payload():
0022             for subsubpart in subpart.walk():
0023                 yield subsubpart
0024 
0025 
0026 
0027 # These two functions are imported into the Iterators.py interface module.
0028 # The Python 2.2 version uses generators for efficiency.
0029 def body_line_iterator(msg, decode=False):
0030     """Iterate over the parts, returning string payloads line-by-line.
0031 
0032     Optional decode (default False) is passed through to .get_payload().
0033     """
0034     for subpart in msg.walk():
0035         payload = subpart.get_payload(decode=decode)
0036         if isinstance(payload, basestring):
0037             for line in StringIO(payload):
0038                 yield line
0039 
0040 
0041 def typed_subpart_iterator(msg, maintype='text', subtype=None):
0042     """Iterate over the subparts with a given MIME type.
0043 
0044     Use `maintype' as the main MIME type to match against; this defaults to
0045     "text".  Optional `subtype' is the MIME subtype to match against; if
0046     omitted, only the main type is matched.
0047     """
0048     for subpart in msg.walk():
0049         if subpart.get_content_maintype() == maintype:
0050             if subtype is None or subpart.get_content_subtype() == subtype:
0051                 yield subpart
0052 
0053 
0054 
0055 def _structure(msg, fp=None, level=0, include_default=False):
0056     """A handy debugging aid"""
0057     if fp is None:
0058         fp = sys.stdout
0059     tab = ' ' * (level * 4)
0060     print >> fp, tab + msg.get_content_type(),
0061     if include_default:
0062         print >> fp, '[%s]' % msg.get_default_type()
0063     else:
0064         print >> fp
0065     if msg.is_multipart():
0066         for subpart in msg.get_payload():
0067             _structure(subpart, fp, level+1, include_default)
0068 

Generated by PyXR 0.9.4
SourceForge.net Logo