iterators.py 2.2 KB

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