I am monitoring a file in Python and triggering an action when it reaches a certain size. Right now I am sleeping and polling but I’m sure there is a more elegant way to do this:
POLLING_PERIOD = 10
SIZE_LIMIT = 1 * 1024 * 1024
while True:
sleep(POLLING_PERIOD)
if stat(file).st_size >= SIZE_LIMIT:
# do something
The thing is, if I have a big POLLING_PERIOD, my file limit is not accurate if the file grows quickly, but if I have a small POLLING_PERIOD, I am wasting CPU.
Thanks!
How can I do this?
Thanks!
Linux Solution
You want to look at using pyinotify it is a Python binding for inotify.
Here is an example on watching for
closeevents, it isn’t a big jump to listening for size changes.Windows Solution
pywin32 has bindings for file system notifications for the Windows file system.
What you want to look for is using FindFirstChangeNotification and tie into that and list for
FILE_NOTIFY_CHANGE_SIZE. This example listens for File Name change it isn’t a big leap to listen for size changes.OSX Solution
There is equivalent hooks into the OSX file system using PyKQueue as well, but if you can understand these examples you can Google for the OSX solution as well.
Here is a good article about Cross Platform File System Monitoring.