File Polling (Rereading)
John Taylor
john_taylor_1973 at yahoo.com
Sat Oct 23 01:20:45 EDT 2004
Daniel Mueller <da_mueller at gmx.net> wrote in message news:<cl85jb$2rfa$1 at news.imp.ch>...
> Hello Fellow Python Programmers,
>
> I have the following problem:
>
> i want to read the content of a file every 10 seconds. now what is the
> best funktion to do that? to open the file, read it and close it
> consumes a lot of CPU time. is there a better solution?
>
> Greetings Daniel
Daniel,
I have written a python program that does this. It does not use a lot
of CPU cycles. You need to change the SLEEP variable from 0.50 to 10.
I have used it on Windows and on Linux. Here it is...
-John
#!/usr/bin/env python
"""
tail.py
John Taylor, Oct 19 2004
Adapted from:
http://groups.google.com/groups?hl=en&lr=&selm=mailman.1028401086.15956.python-list%40python.org
"""
import sys,os,time,stat
SLEEP = 0.50
if len(sys.argv) != 2:
print
print "tail.py [ filename ]"
print
sys.exit(1)
FILENAME = sys.argv[1]
try:
fd = os.open(FILENAME,os.O_RDONLY) # on Linux, may want |O_LARGEFILE
except OSError, e:
print e
sys.exit(1)
info = os.fstat( fd )
lastsize = info[stat.ST_SIZE]
os.lseek( fd, lastsize, 2 )
try:
while True:
info = os.fstat( fd )
size = info[stat.ST_SIZE]
if size > lastsize:
os.lseek(fd, lastsize, 0)
data = os.read(fd, size - lastsize)
print data,
lastsize=size
time.sleep( SLEEP )
except KeyboardInterrupt:
pass
# end of program
More information about the Python-list
mailing list