Project

General

Profile

« Previous | Next » 

Revision 1682

streams.py: Added CaptureStream to wrap a stream, capturing matching text. Renamed TracedOutputStream to TracedStream and made it work on both input and output streams. Made TracedStream inherit from WrapStream so that close() would be forwarded properly.

View differences:

lib/streams.py
38 38
    def readline(self):
39 39
        return timeouts.run(lambda: self.stream.readline(), self.timeout)
40 40

  
41
class TracedOutputStream:
42
    '''Wraps an output stream, running a trace function on each string written
41
class TracedStream(WrapStream):
42
    '''Wraps a stream, running a trace function on each string read or written
43 43
    '''
44 44
    def __init__(self, trace, stream):
45
        WrapStream.__init__(self, stream)
45 46
        self.trace = trace
46
        self.stream = stream
47 47
    
48
    def readline(self):
49
        str_ = self.stream.readline()
50
        self.trace(str_)
51
        return str_
52
    
48 53
    def write(self, str_):
49 54
        self.trace(str_)
50 55
        return self.stream.write(str_)
51 56

  
52
class LineCountOutputStream(TracedOutputStream):
57
class LineCountOutputStream(TracedStream):
53 58
    '''Wraps an output stream, making the current line number available.
54 59
    Lines start counting from 1.'''
55 60
    def __init__(self, stream):
56 61
        self.line_num = 1
57 62
        def trace(str_): self.line_num += str_.count('\n')
58
        TracedOutputStream.__init__(self, trace, stream)
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)

Also available in: Unified diff