Created
September 2, 2009 15:18
-
-
Save maio/179758 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def get_last_lines(fp, num, step=10): | |
pos = step | |
lines = [] | |
quit = False | |
while len(lines) < num + 1 and not quit: | |
fp.seek(-pos, 2) | |
if int(fp.tell()) == 0: | |
quit = True | |
lines = fp.readlines() | |
pos = pos + step | |
return lines[-num:] | |
import unittest | |
from StringIO import StringIO | |
class TestGetLastLines(unittest.TestCase): | |
def setUp(self): | |
self.fp = StringIO("line1\nline2\nline3\n") | |
def test_get(self): | |
# jeden | |
self.assertEqual(get_last_lines(self.fp, 1), ['line3\n']) | |
# dva riadky | |
self.assertEqual( | |
get_last_lines(self.fp, 2), | |
['line2\n', 'line3\n']) | |
# sto | |
self.assertEqual( | |
get_last_lines(self.fp, 100), | |
['line1\n', 'line2\n', 'line3\n']) | |
if __name__ == '__main__': | |
unittest.main() | |
$ python last2.py | |
. | |
---------------------------------------------------------------------- | |
Ran 1 test in 0.000s | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment