- Notifications
You must be signed in to change notification settings - Fork 31.7k
/
Copy pathiterators.py
68 lines (54 loc) · 2.08 KB
/
iterators.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Various types of useful iterators and generators."""
__all__= [
'body_line_iterator',
'typed_subpart_iterator',
'walk',
# Do not include _structure() since it's part of the debugging API.
]
importsys
fromioimportStringIO
# This function will become a method of the Message class
defwalk(self):
"""Walk over the message tree, yielding each subpart.
The walk is performed in depth-first order. This method is a
generator.
"""
yieldself
ifself.is_multipart():
forsubpartinself.get_payload():
yieldfromsubpart.walk()
# These two functions are imported into the Iterators.py interface module.
defbody_line_iterator(msg, decode=False):
"""Iterate over the parts, returning string payloads line-by-line.
Optional decode (default False) is passed through to .get_payload().
"""
forsubpartinmsg.walk():
payload=subpart.get_payload(decode=decode)
ifisinstance(payload, str):
yieldfromStringIO(payload)
deftyped_subpart_iterator(msg, maintype='text', subtype=None):
"""Iterate over the subparts with a given MIME type.
Use `maintype' as the main MIME type to match against; this defaults to
"text". Optional `subtype' is the MIME subtype to match against; if
omitted, only the main type is matched.
"""
forsubpartinmsg.walk():
ifsubpart.get_content_maintype() ==maintype:
ifsubtypeisNoneorsubpart.get_content_subtype() ==subtype:
yieldsubpart
def_structure(msg, fp=None, level=0, include_default=False):
"""A handy debugging aid"""
iffpisNone:
fp=sys.stdout
tab=' '* (level*4)
print(tab+msg.get_content_type(), end='', file=fp)
ifinclude_default:
print(' [%s]'%msg.get_default_type(), file=fp)
else:
print(file=fp)
ifmsg.is_multipart():
forsubpartinmsg.get_payload():
_structure(subpart, fp, level+1, include_default)