I am trying to read a syslog repeatedly and only start from the point I left off last read. I am trying to save the location of tell() is a sperate file and reload to seek before every read.
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()
Write
str(last_loc)
instead oflast_loc
.The rest are probably optional.
- Use
w
instead ofw+
for writing the location. - Close
/var/log/messages
when you're done with it. - Depending on your version of Python (definitely on 2.6 or newer, maybe on 2.5 depending), you may want to use
with
to automatially close files. - You probably don't need
strip
if you're just writing the value. - You can just use
read
instead ofreadline
onlf
. You can iterate over the file itself, rather than using
readlines
, forsl
.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))
Your readline is weird. What you nee to do is either:
1) save the value as a string and parse it:
lf.write(str(last_loc))
2) save and reread the location as an int:
lf.write(struct.pack("Q",lf.tell()))
last_pos = struct.unpack("Q",lf.read())
精彩评论