challenge tailの実装

'tail'を実装してください。

巨大なファイルでも効率的に動作するようにしてください。

最低限必要な機能は、

  • 行数指定
  • 「-f」パラメータの対応

です。

Posted feedbacks - Python

手抜きで行末記号を"\n"で決め打ちです。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import sys
import time
import StringIO

def gettail(fp, n):
  start = fp.tell()
  fp.seek(0, 2)
  end = fp.tell()
  s = ''
  while len(s) < end - start and s.count('\n') <= n:
    a = min(160 * n, fp.tell() - start)
    fp.seek(-a, 1)
    s = fp.read(a) + s
  return StringIO.StringIO(s).readlines()[-n:]

def getnlines(fp, start, n):
  fp.seek(0, 2)
  pos = fp.tell()
  fp.seek(start)
  for s in gettail(fp, n):
    sys.stdout.write(s)
    sys.stdout.flush()
  return pos

n = 10
f = False
fp = None

sys.argv.pop(0)
while sys.argv:
  s = sys.argv.pop(0)
  if s == '-n':
    n = int(sys.argv.pop(0))
  elif s == '-f':
    f = True
  elif not s.startswith('-'):
    fp = file(s, 'rb')

pos = getnlines(fp, 0, n)

while f:
  time.sleep(1)
  pos = getnlines(fp, pos, n)

Index

Feed

Other

Link

Pathtraq

loading...