ยปCore Development>Code coverage>Lib/email/iterators.py

Python code coverage for Lib/email/iterators.py

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