Reputation: 167
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()
Upvotes: 3
Views: 791
Reputation: 176730
Write str(last_loc)
instead of last_loc
.
The rest are probably optional.
w
instead of w+
for writing the location./var/log/messages
when you're done with it.with
to automatially close files.strip
if you're just writing the value.read
instead of readline
on lf
.You can iterate over the file itself, rather than using readlines
, for 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))
Upvotes: 3
Reputation: 26251
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())
Upvotes: 0