Revision 5592
Added by Aaron Marcuse-Kubitza over 12 years ago
lib/streams.py | ||
---|---|---|
88 | 88 |
|
89 | 89 |
class LineCountStream(TracedStream): |
90 | 90 |
'''Wraps a unidirectional stream, making the current line number available. |
91 |
Lines start counting from 1.''' |
|
91 |
Lines start counting from 1, incrementing before each line is returned.'''
|
|
92 | 92 |
def __init__(self, stream): |
93 |
self.line_num = 1
|
|
93 |
self.line_num = 0
|
|
94 | 94 |
def trace(str_): self.line_num += str_.count('\n') |
95 | 95 |
TracedStream.__init__(self, trace, stream) |
96 | 96 |
|
97 | 97 |
class LineCountInputStream(TracedStream): |
98 | 98 |
'''Wraps an input stream, making the current line number available. |
99 |
Lines start counting from 1. |
|
99 |
Lines start counting from 1, incrementing before each line is returned.
|
|
100 | 100 |
This is faster than LineCountStream for input streams, because all reading |
101 | 101 |
is done through readline() so newlines don't need to be explicitly counted. |
102 | 102 |
''' |
103 | 103 |
def __init__(self, stream): |
104 |
self.line_num = 1
|
|
104 |
self.line_num = 0
|
|
105 | 105 |
def trace(str_): |
106 | 106 |
if str_ != '': self.line_num += 1 # EOF is not a line |
107 | 107 |
TracedStream.__init__(self, trace, stream) |
... | ... | |
127 | 127 |
if eof: line_ending = '\n' |
128 | 128 |
else: line_ending = '\r' |
129 | 129 |
|
130 |
line_ct = self.stream.line_num - 1 # make it 0-based |
|
131 |
if eof or line_ct % n == 0: log.write((msg_ % line_ct)+line_ending) |
|
130 |
line_ct = self.stream.line_num |
|
131 |
if eof or (line_ct > 0 and line_ct % n == 0): |
|
132 |
log.write((msg_ % line_ct)+line_ending) |
|
132 | 133 |
self.trace = trace |
133 | 134 |
|
134 | 135 |
TracedStream.__init__(self, trace, LineCountInputStream(stream)) |
Also available in: Unified diff
streams.py: LineCountStream, LineCountInputStream: Fixed bug where line_num was 1 too high because it started at 1 and was incremented before each line is returned. It now properly starts at 1, but the initial line_num value is 0 to increment to 1 upon encountering the first line. This off-by-one behavior may have been needed for code that associates an error message with a line #, but such code should add 1 to the line_num to get the line # of the error if the error prevents the next line from being read by the LineCount*Stream.