source: trunk/essentials/dev-lang/python/Lib/email/iterators.py

Last change on this file was 3225, checked in by bird, 19 years ago

Python 2.5

File size: 2.2 KB
Line 
1# Copyright (C) 2001-2006 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: [email protected]
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
14import sys
15from cStringIO import StringIO
16
17
18
19
20# This function will become a method of the Message class
21def 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
35
36# These two functions are imported into the Iterators.py interface module.
37def 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
49def 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
63
64def _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)
Note: See TracBrowser for help on using the repository browser.