1 # Copyright (C) 2001-2006 Python Software Foundation 2 # Author: Barry Warsaw 3 # Contact: email-sig (at] python.org 4 5 """Various types of useful iterators and generators.""" 6 7 __all__ = [ 8 'body_line_iterator', 9 'typed_subpart_iterator', 10 'walk', 11 # Do not include _structure() since it's part of the debugging API. 12 ] 13 14 import sys 15 from cStringIO import StringIO 16 17 18 20 # This function will become a method of the Message class 21 def walk(self): 22 """Walk over the message tree, yielding each subpart. 23 24 The walk is performed in depth-first order. This method is a 25 generator. 26 """ 27 yield self 28 if self.is_multipart(): 29 for subpart in self.get_payload(): 30 for subsubpart in subpart.walk(): 31 yield subsubpart 32 33 34 36 # These two functions are imported into the Iterators.py interface module. 37 def body_line_iterator(msg, decode=False): 38 """Iterate over the parts, returning string payloads line-by-line. 39 40 Optional decode (default False) is passed through to .get_payload(). 41 """ 42 for subpart in msg.walk(): 43 payload = subpart.get_payload(decode=decode) 44 if isinstance(payload, basestring): 45 for line in StringIO(payload): 46 yield line 47 48 49 def typed_subpart_iterator(msg, maintype='text', subtype=None): 50 """Iterate over the subparts with a given MIME type. 51 52 Use `maintype' as the main MIME type to match against; this defaults to 53 "text". Optional `subtype' is the MIME subtype to match against; if 54 omitted, only the main type is matched. 55 """ 56 for subpart in msg.walk(): 57 if subpart.get_content_maintype() == maintype: 58 if subtype is None or subpart.get_content_subtype() == subtype: 59 yield subpart 60 61 62 64 def _structure(msg, fp=None, level=0, include_default=False): 65 """A handy debugging aid""" 66 if fp is None: 67 fp = sys.stdout 68 tab = ' ' * (level * 4) 69 print >> fp, tab + msg.get_content_type(), 70 if include_default: 71 print >> fp, '[%s]' % msg.get_default_type() 72 else: 73 print >> fp 74 if msg.is_multipart(): 75 for subpart in msg.get_payload(): 76 _structure(subpart, fp, level+1, include_default) 77