Deprecated since version 2.5: The email package should be used in preference to the multifile module. This module is present only to maintain backward compatibility.
The MultiFile object enables you to treat sections of a text file as file-like input objects, with '' being returned by readline() when a given delimiter pattern is encountered. The defaults of this class are designed to make it useful for parsing MIME multipart messages, but by subclassing it and overriding methods it can be easily adapted for more general use.
MultiFile only ever looks at the input object’s readline(), seek() and tell() methods, and the latter two are only needed if you want random access to the individual MIME parts. To use MultiFile on a non-seekable stream object, set the optional seekable argument to false; this will prevent using the input object’s seek() and tell() methods.
It will be useful to know that in MultiFile‘s view of the world, text is composed of three kinds of lines: data, section-dividers, and end-markers. MultiFile is designed to support parsing of messages that may have multiple nested message parts, each with its own pattern for section-divider and end-marker lines.
A MultiFile instance has the following methods:
Return true if str is data and false if it might be a section boundary. As written, it tests for a prefix other than '--' at start of line (which all MIME boundaries have) but it is declared so it can be overridden in derived classes.
Note that this test is used intended as a fast guard for the real boundary tests; if it always returns false it will merely slow processing, not cause it to fail.
Push a boundary string. When a decorated version of this boundary is found as an input line, it will be interpreted as a section-divider or end-marker (depending on the decoration, see RFC 2045). All subsequent reads will return the empty string to indicate end-of-file, until a call to pop() removes the boundary a or next() call reenables it.
It is possible to push more than one boundary. Encountering the most-recently-pushed boundary will return EOF; encountering any other boundary will raise an error.
Finally, MultiFile instances have two public instance variables:
import mimetools import multifile import StringIO def extract_mime_part_matching(stream, mimetype): """Return the first element in a multipart MIME message on stream matching mimetype.""" msg = mimetools.Message(stream) msgtype = msg.gettype() params = msg.getplist() data = StringIO.StringIO() if msgtype[:10] == "multipart/": file = multifile.MultiFile(stream) file.push(msg.getparam("boundary")) while file.next(): submsg = mimetools.Message(file) try: data = StringIO.StringIO() mimetools.decode(file, data, submsg.getencoding()) except ValueError: continue if submsg.gettype() == mimetype: break file.pop() return data.getvalue()