1 """A readline()-style interface to the parts of a multipart message.
3 The MultiFile class makes each part of a multipart message "feel" like
4 an ordinary file, as long as you use fp.readline(). Allows recursive
5 use, for nested multipart messages. Probably best used together
11 fp = MultiFile(real_fp)
13 "read some lines from fp"
16 "read lines from fp until it returns an empty string" (A)
17 if not fp.next(): break
19 "read remaining lines from fp until it returns an empty string"
21 The latter sequence may be used recursively at (A).
22 It is also allowed to use multiple push()...pop() sequences.
24 If seekable is given as 0, the class code will not do the bookkeeping
25 it normally attempts in order to make seeks relative to the beginning of the
26 current file part. This may be useful when using MultiFile with a non-
27 seekable stream object.
30 __all__
= ["MultiFile","Error"]
32 class Error(Exception):
39 def __init__(self
, fp
, seekable
=1):
46 self
.start
= self
.fp
.tell()
52 return self
.fp
.tell() - self
.start
54 def seek(self
, pos
, whence
=0):
61 pos
= pos
+ self
.lastpos
63 raise Error
, "can't use whence=2 yet"
64 if not 0 <= pos
<= here
or \
65 self
.level
> 0 and pos
> self
.lastpos
:
66 raise Error
, 'bad MultiFile.seek() call'
67 self
.fp
.seek(pos
+ self
.start
)
74 line
= self
.fp
.readline()
77 self
.level
= len(self
.stack
)
78 self
.last
= (self
.level
> 0)
80 raise Error
, 'sudden EOF in MultiFile.readline()'
82 assert self
.level
== 0
83 # Fast check to see if this is just data
84 if self
.is_data(line
):
87 # Ignore trailing whitespace on marker lines
88 marker
= line
.rstrip()
89 # No? OK, try to match a boundary.
90 # Return the line (unstripped) if we don't.
91 for i
, sep
in enumerate(reversed(self
.stack
)):
92 if marker
== self
.section_divider(sep
):
95 elif marker
== self
.end_marker(sep
):
100 # We only get here if we see a section divider or EOM line
102 self
.lastpos
= self
.tell() - len(line
)
105 raise Error
,'Missing endmarker in MultiFile.readline()'
111 line
= self
.readline()
116 def read(self
): # Note: no size argument -- read until EOF only!
117 return ''.join(self
.readlines())
120 while self
.readline(): pass
121 if self
.level
> 1 or self
.last
:
126 self
.start
= self
.fp
.tell()
131 raise Error
, 'bad MultiFile.push() call'
132 self
.stack
.append(sep
)
134 self
.posstack
.append(self
.start
)
135 self
.start
= self
.fp
.tell()
139 raise Error
, 'bad MultiFile.pop() call'
143 abslastpos
= self
.lastpos
+ self
.start
144 self
.level
= max(0, self
.level
- 1)
147 self
.start
= self
.posstack
.pop()
149 self
.lastpos
= abslastpos
- self
.start
151 def is_data(self
, line
):
152 return line
[:2] != '--'
154 def section_divider(self
, str):
157 def end_marker(self
, str):
158 return "--" + str + "--"