2011-08-14 4 views
3

syslog를 반복적으로 읽으려고하고 마지막으로 읽지 않은 지점부터 시작하려고합니다. 나는 tell()의 위치를 ​​저장하려고 시도하고있다. 모든 파일을 읽기 전에 찾기를 원한다.마지막 위치에서 파일을 반복적으로 읽는 방법

 


    lf = open("location.file", 'r') 
    s = lf.readline() 
    last_pos = int(s.strip()) 
    lf.close() 

    sl = open("/var/log/messages", 'r') 
    sl.seek(last_pos) 
    for line in sl.readlines(): 
     # This should be the starting point from the last read 
    last_loc = sl.tell() 

    lf = open("location.file", "w+") 
    lf.write(last_loc) 
    lf.close() 

 

답변

3
  1. 쓰기 대신 last_locstr(last_loc).

    나머지는 선택 사항입니다.

  2. 위치 쓰기에 w+ 대신 w을 사용하십시오.
  3. 끝내면 /var/log/messages을 닫습니다.
  4. Python의 버전 (확실히 2.6 이상, 아마도 2.5에 따라 다름)에 따라 with을 사용하여 파일을 자동으로 닫을 수 있습니다.
  5. 방금 ​​값을 쓰고 계시다면 아마도 strip이 필요하지 않을 것입니다.
  6. readline 대신 readlf에 사용할 수 있습니다.
  7. readlines을 사용하는 대신 sl을 사용하여 파일 자체를 반복 할 수 있습니다.

    try: 
        with open("location.file") as lf: 
         s = lf.read() 
         last_pos = int(s) 
    except: 
        last_post = 0 
    
    with open("/var/log/messages") as sl: 
        sl.seek(last_pos) 
        for line in sl: 
         # This should be the starting point from the last read 
        last_loc = sl.tell() 
    
    with open("location.file", "w") as lf: 
        lf.write(str(last_loc)) 
    
+1

try: \t with open("location.file") as lf: \t \t s = lf.read() \t \t last_pos = int(s) except: \t \t last_pos = 0;

+0

당신은 코멘트에 backticks를 사용해야하지만, 그렇지 않으면 좋은 제안. – agf

0

귀하의 readline 이상한입니다. 당신이해야 할 태어나 셨 것은 중 하나입니다 :

1) 문자열로 값을 저장하고 분석 :

lf.write(str(last_loc)) 

2)를 저장하고 int로서 위치를 다시 읽어 :

lf.write(struct.pack("Q",lf.tell())) 
last_pos = struct.unpack("Q",lf.read()) 
+0

아직도 파일에 int를 쓰는 방법을 보여주지 못했습니다. :) – agf