Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/email/iterators.py: 27%
30 statements
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
« prev ^ index » next coverage.py v7.0.5, created at 2023-01-17 06:13 +0000
1# Copyright (C) 2001-2006 Python Software Foundation
2# Author: Barry Warsaw
3# Contact: email-sig@python.org
5"""Various types of useful iterators and generators."""
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 ]
14import sys
15from io import StringIO
19# This function will become a method of the Message class
20def walk(self):
21 """Walk over the message tree, yielding each subpart.
23 The walk is performed in depth-first order. This method is a
24 generator.
25 """
26 yield self
27 if self.is_multipart():
28 for subpart in self.get_payload():
29 yield from subpart.walk()
33# These two functions are imported into the Iterators.py interface module.
34def body_line_iterator(msg, decode=False):
35 """Iterate over the parts, returning string payloads line-by-line.
37 Optional decode (default False) is passed through to .get_payload().
38 """
39 for subpart in msg.walk():
40 payload = subpart.get_payload(decode=decode)
41 if isinstance(payload, str):
42 yield from StringIO(payload)
45def typed_subpart_iterator(msg, maintype='text', subtype=None):
46 """Iterate over the subparts with a given MIME type.
48 Use `maintype' as the main MIME type to match against; this defaults to
49 "text". Optional `subtype' is the MIME subtype to match against; if
50 omitted, only the main type is matched.
51 """
52 for subpart in msg.walk():
53 if subpart.get_content_maintype() == maintype:
54 if subtype is None or subpart.get_content_subtype() == subtype:
55 yield subpart
59def _structure(msg, fp=None, level=0, include_default=False):
60 """A handy debugging aid"""
61 if fp is None:
62 fp = sys.stdout
63 tab = ' ' * (level * 4)
64 print(tab + msg.get_content_type(), end='', file=fp)
65 if include_default:
66 print(' [%s]' % msg.get_default_type(), file=fp)
67 else:
68 print(file=fp)
69 if msg.is_multipart():
70 for subpart in msg.get_payload():
71 _structure(subpart, fp, level+1, include_default)