File Polling (Rereading)

Oliver Fromme olli at haluter.fromme.com
Thu Oct 21 09:01:19 EDT 2004


Daniel Mueller <da_mueller at gmx.net> wrote:
 > 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?

The portable way is to stat the file (see os.stat) every
10 seconds, look at the mtime (modification time), and
if it did change, then open/read/close.  This still means
polling the file, but at least stat is much more efficient
than open/read/close.  If you're also interested in changes
to the metainformations of the file (permissions, owner
etc.), you also have to look at the ctime.

If you're lucky enough to work on a FreeBSD UNIX system
(and don't need a portable solution), you can use FreeBSD's
kqueue API.  Using that interface, you don't have to poll
at all.  The kernel will notify you immediately when a
specific event occurs, such as someone writing to a certain
file (this is used by the "tail -f" command, for example,
so it doesn't have to poll the file).  The Python bindings
for the kqueue interface are in the ports collection of
FreeBSD (see ports/devel/kqueue).  Otherwise, see this
webpage for more information:

http://people.freebsd.org/~dwhite/PyKQueue/

Best regards
   Oliver

-- 
Oliver Fromme, Konrad-Celtis-Str. 72, 81369 Munich, Germany

``All that we see or seem is just a dream within a dream.''
(E. A. Poe)



More information about the Python-list mailing list