Skip to content

Instantly share code, notes, and snippets.

@maio
Created September 2, 2009 15:18
Show Gist options
  • Save maio/179758 to your computer and use it in GitHub Desktop.
Save maio/179758 to your computer and use it in GitHub Desktop.
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