1 # Copyright (C) 2001-2006 Python Software Foundation
3 # Contact: email-sig@python.org
5 """Various types of useful iterators and generators."""
9 'typed_subpart_iterator',
11 # Do not include _structure() since it's part of the debugging API.
15 from cStringIO
import StringIO
19 # This function will become a method of the Message class
21 """Walk over the message tree, yielding each subpart.
23 The walk is performed in depth-first order. This method is a
27 if self
.is_multipart():
28 for subpart
in self
.get_payload():
29 for subsubpart
in subpart
.walk():
34 # These two functions are imported into the Iterators.py interface module.
35 def body_line_iterator(msg
, decode
=False):
36 """Iterate over the parts, returning string payloads line-by-line.
38 Optional decode (default False) is passed through to .get_payload().
40 for subpart
in msg
.walk():
41 payload
= subpart
.get_payload(decode
=decode
)
42 if isinstance(payload
, basestring
):
43 for line
in StringIO(payload
):
47 def typed_subpart_iterator(msg
, maintype
='text', subtype
=None):
48 """Iterate over the subparts with a given MIME type.
50 Use `maintype' as the main MIME type to match against; this defaults to
51 "text". Optional `subtype' is the MIME subtype to match against; if
52 omitted, only the main type is matched.
54 for subpart
in msg
.walk():
55 if subpart
.get_content_maintype() == maintype
:
56 if subtype
is None or subpart
.get_content_subtype() == subtype
:
61 def _structure(msg
, fp
=None, level
=0, include_default
=False):
62 """A handy debugging aid"""
65 tab
= ' ' * (level
* 4)
66 print >> fp
, tab
+ msg
.get_content_type(),
68 print >> fp
, '[%s]' % msg
.get_default_type()
71 if msg
.is_multipart():
72 for subpart
in msg
.get_payload():
73 _structure(subpart
, fp
, level
+1, include_default
)