Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6149663
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T19:29:27+00:00 2026-05-23T19:29:27+00:00

I am monitoring a file in Python and triggering an action when it reaches

  • 0

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!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T19:29:29+00:00Added an answer on May 23, 2026 at 7:29 pm

    Linux Solution

    You want to look at using pyinotify it is a Python binding for inotify.

    Here is an example on watching for close events, it isn’t a big jump to listening for size changes.

    #!/usr/bin/env python
    
    import os, sys
    from pyinotify import WatchManager, Notifier, ProcessEvent, EventsCodes
    
    def Monitor(path):
        class PClose(ProcessEvent):
            def process_IN_CLOSE(self, event):
                f = event.name and os.path.join(event.path, event.name) or event.path
                print 'close event: ' + f
    
        wm = WatchManager()
        notifier = Notifier(wm, PClose())
        wm.add_watch(path, EventsCodes.IN_CLOSE_WRITE|EventsCodes.IN_CLOSE_NOWRITE)
    
        try:
            while 1:
                notifier.process_events()
                if notifier.check_events():
                    notifier.read_events()
        except KeyboardInterrupt:
            notifier.stop()
            return
    
    
    if __name__ == '__main__':
        try:
            path = sys.argv[1]
        except IndexError:
            print 'use: %s dir' % sys.argv[0]
        else:
            Monitor(path)
    

    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.

    import os
    
    import win32file
    import win32event
    import win32con
    
    path_to_watch = os.path.abspath (".")
    
    #
    # FindFirstChangeNotification sets up a handle for watching
    #  file changes. The first parameter is the path to be
    #  watched; the second is a boolean indicating whether the
    #  directories underneath the one specified are to be watched;
    #  the third is a list of flags as to what kind of changes to
    #  watch for. We're just looking at file additions / deletions.
    #
    change_handle = win32file.FindFirstChangeNotification (
      path_to_watch,
      0,
      win32con.FILE_NOTIFY_CHANGE_FILE_NAME
    )
    
    #
    # Loop forever, listing any file changes. The WaitFor... will
    #  time out every half a second allowing for keyboard interrupts
    #  to terminate the loop.
    #
    try:
    
      old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
      while 1:
        result = win32event.WaitForSingleObject (change_handle, 500)
    
        #
        # If the WaitFor... returned because of a notification (as
        #  opposed to timing out or some error) then look for the
        #  changes in the directory contents.
        #
        if result == win32con.WAIT_OBJECT_0:
          new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
          added = [f for f in new_path_contents if not f in old_path_contents]
          deleted = [f for f in old_path_contents if not f in new_path_contents]
          if added: print "Added: ", ", ".join (added)
          if deleted: print "Deleted: ", ", ".join (deleted)
    
          old_path_contents = new_path_contents
          win32file.FindNextChangeNotification (change_handle)
    
    finally:
      win32file.FindCloseChangeNotification (change_handle)
    

    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.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Java 7 introduced WatchService for monitoring file systems continuously. Is there a backport for
I'm looking for a cross-platform file monitoring python package? I know it is possible
Is there a portable way of monitoring a file for changes from a deployed
Currently I monitoring a particular file with a simple shell one-liner: filesize=$(ls -lah somefile
I am monitoring a folder with a .net filewatcher for certain kind of files(*.mbxml).
I did some HTTP monitoring with WireShark. Are there more tools like this that
I wrote a CPU monitoring program in Python. For some reason sometimes the the
Are there any patterns or practices for monitoring log4net exception logs across a cluster
For some odd reason, the apc file upload status gives me the file size
I have a shell script file for monitoring my application, this script will be

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.