2011-08-14 9 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. str(last_loc)の代わりlast_locを書きます。

    残りはおそらくオプションです。

  2. w+の代わりにwを使用して場所を書きます。
  3. 完了したら/var/log/messagesを終了してください。
  4. Pythonのバージョン(間違いなく2.6以上、おそらく2.5に依存)に応じて、withを使用してファイルを自動的に閉じることができます。
  5. 値を書き込んでいるのであれば、おそらくstripは必要ありません。
  6. readlineの代わりにreadを使用できます。
  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

コメントにバッククッキーを使用する必要がありますが、そうでなければ良い提案です。 – 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

関連する問題