1
|
# I/O
|
2
|
|
3
|
import timeouts
|
4
|
|
5
|
class WrapStream:
|
6
|
'''Forwards close() to the underlying stream'''
|
7
|
def __init__(self, stream): self.stream = stream
|
8
|
|
9
|
def close(self): self.stream.close()
|
10
|
|
11
|
class StreamIter(WrapStream):
|
12
|
'''Iterates over the lines in a stream.
|
13
|
Unlike stream.__iter__(), doesn't wait for EOF to start returning lines.
|
14
|
Offers curr() method.
|
15
|
'''
|
16
|
def __init__(self, stream):
|
17
|
WrapStream.__init__(self, stream)
|
18
|
self.line = None
|
19
|
|
20
|
def __iter__(self): return self
|
21
|
|
22
|
def curr(self):
|
23
|
if self.line == None: self.line = self.stream.readline()
|
24
|
if self.line == '': raise StopIteration
|
25
|
return self.line
|
26
|
|
27
|
def next(self):
|
28
|
line = self.curr()
|
29
|
self.line = None
|
30
|
return line
|
31
|
|
32
|
class TimeoutInputStream(WrapStream):
|
33
|
'''@param timeout sec'''
|
34
|
def __init__(self, stream, timeout):
|
35
|
WrapStream.__init__(self, stream)
|
36
|
self.timeout = timeout
|
37
|
|
38
|
def readline(self):
|
39
|
return timeouts.run(lambda: self.stream.readline(), self.timeout)
|
40
|
|
41
|
class TracedStream(WrapStream):
|
42
|
'''Wraps a stream, running a trace function on each string read or written
|
43
|
'''
|
44
|
def __init__(self, trace, stream):
|
45
|
WrapStream.__init__(self, stream)
|
46
|
self.trace = trace
|
47
|
|
48
|
def readline(self):
|
49
|
str_ = self.stream.readline()
|
50
|
self.trace(str_)
|
51
|
return str_
|
52
|
|
53
|
def write(self, str_):
|
54
|
self.trace(str_)
|
55
|
return self.stream.write(str_)
|
56
|
|
57
|
class LineCountOutputStream(TracedStream):
|
58
|
'''Wraps an output stream, making the current line number available.
|
59
|
Lines start counting from 1.'''
|
60
|
def __init__(self, stream):
|
61
|
self.line_num = 1
|
62
|
def trace(str_): self.line_num += str_.count('\n')
|
63
|
TracedStream.__init__(self, trace, stream)
|
64
|
|
65
|
class CaptureStream(TracedStream):
|
66
|
'''Wraps a stream, capturing matching text.
|
67
|
Matched text can be retrieved from self.match.'''
|
68
|
def __init__(self, stream, start_str, end_str):
|
69
|
self.recording = False
|
70
|
self.match = ''
|
71
|
|
72
|
def trace(str_):
|
73
|
start_idx = str_.find(start_str)
|
74
|
if start_idx >= 0: self.recording = True
|
75
|
else: start_idx = 0
|
76
|
|
77
|
recording = self.recording # save recording status
|
78
|
|
79
|
end_idx = str_.find(end_str)
|
80
|
if end_idx >= 0:
|
81
|
self.recording = False
|
82
|
end_idx += len(end_str)
|
83
|
else: end_idx = len(str_)
|
84
|
|
85
|
if recording: self.match += str_[start_idx:end_idx]
|
86
|
|
87
|
TracedStream.__init__(self, trace, stream)
|