1 |
1630
|
aaronmk
|
# I/O
|
2 |
|
|
|
3 |
|
|
class StreamIter:
|
4 |
|
|
'''Iterates over the lines in a stream.
|
5 |
|
|
Unlike stream.__iter__(), doesn't wait for EOF to start returning lines.
|
6 |
|
|
Offers curr() method.
|
7 |
|
|
Forwards close() to the underlying stream.
|
8 |
|
|
'''
|
9 |
|
|
def __init__(self, stream):
|
10 |
|
|
self.stream = stream
|
11 |
|
|
self.line = None
|
12 |
|
|
|
13 |
|
|
def __iter__(self): return self
|
14 |
|
|
|
15 |
|
|
def curr(self):
|
16 |
|
|
if self.line == None: self.line = self.stream.readline()
|
17 |
|
|
if self.line == '': raise StopIteration
|
18 |
|
|
return self.line
|
19 |
|
|
|
20 |
|
|
def next(self):
|
21 |
|
|
line = self.curr()
|
22 |
|
|
self.line = None
|
23 |
|
|
return line
|
24 |
|
|
|
25 |
|
|
def close(self): self.stream.close()
|
26 |
|
|
|
27 |
|
|
class TracedOutputStream:
|
28 |
|
|
'''Wraps an output stream, running a trace function on each string written
|
29 |
|
|
'''
|
30 |
|
|
def __init__(self, trace, stream):
|
31 |
|
|
self.trace = trace
|
32 |
|
|
self.stream = stream
|
33 |
|
|
|
34 |
|
|
def write(self, str_):
|
35 |
|
|
self.trace(str_)
|
36 |
|
|
return self.stream.write(str_)
|
37 |
|
|
|
38 |
|
|
class LineCountOutputStream(TracedOutputStream):
|
39 |
|
|
'''Wraps an output stream, making the current line number available.
|
40 |
|
|
Lines start counting from 1.'''
|
41 |
|
|
def __init__(self, stream):
|
42 |
|
|
self.line_num = 1
|
43 |
|
|
def trace(str_): self.line_num += str_.count('\n')
|
44 |
|
|
TracedOutputStream.__init__(self, trace, stream)
|