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.
33 class Error(Exception):
40 def __init__(self
, fp
, seekable
=1):
42 self
.stack
= [] # Grows down
47 self
.start
= self
.fp
.tell()
48 self
.posstack
= [] # Grows down
53 return self
.fp
.tell() - self
.start
55 def seek(self
, pos
, whence
=0):
62 pos
= pos
+ self
.lastpos
64 raise Error
, "can't use whence=2 yet"
65 if not 0 <= pos
<= here
or \
66 self
.level
> 0 and pos
> self
.lastpos
:
67 raise Error
, 'bad MultiFile.seek() call'
68 self
.fp
.seek(pos
+ self
.start
)
75 line
= self
.fp
.readline()
78 self
.level
= len(self
.stack
)
79 self
.last
= (self
.level
> 0)
81 raise Error
, 'sudden EOF in MultiFile.readline()'
83 assert self
.level
== 0
84 # Fast check to see if this is just data
85 if self
.is_data(line
):
88 # Ignore trailing whitespace on marker lines
90 while line
[k
] in string
.whitespace
:
93 # No? OK, try to match a boundary.
94 # Return the line (unstripped) if we don't.
95 for i
in range(len(self
.stack
)):
97 if marker
== self
.section_divider(sep
):
100 elif marker
== self
.end_marker(sep
):
105 # We only get here if we see a section divider or EOM line
107 self
.lastpos
= self
.tell() - len(line
)
110 raise Error
,'Missing endmarker in MultiFile.readline()'
116 line
= self
.readline()
121 def read(self
): # Note: no size argument -- read until EOF only!
122 return string
.joinfields(self
.readlines(), '')
125 while self
.readline(): pass
126 if self
.level
> 1 or self
.last
:
131 self
.start
= self
.fp
.tell()
136 raise Error
, 'bad MultiFile.push() call'
137 self
.stack
.insert(0, sep
)
139 self
.posstack
.insert(0, self
.start
)
140 self
.start
= self
.fp
.tell()
144 raise Error
, 'bad MultiFile.pop() call'
148 abslastpos
= self
.lastpos
+ self
.start
149 self
.level
= max(0, self
.level
- 1)
152 self
.start
= self
.posstack
[0]
155 self
.lastpos
= abslastpos
- self
.start
157 def is_data(self
, line
):
158 return line
[:2] <> '--'
160 def section_divider(self
, str):
163 def end_marker(self
, str):
164 return "--" + str + "--"