Ex, I need to catch remove and add files events on some directory on linux os. I found libs like inotify and python wrappers for them, but if I want to use clear python code should I watch for os.listdir(path) output every sec or are there some ways to accomplish such task?
Ex, I need to catch remove and add files events on some directory on
Share
Source: http://code.activestate.com/recipes/215418-watching-a-directory-tree-on-unix/
The watch_directories() function takes a list of paths and a callable object, and then repeatedly traverses the directory trees rooted at those paths, watching for files that get deleted or have their modification time changed. The callable object is then passed two lists containing the files that have changed and the files that have been removed.
This recipe is useful where you’d like some way to send jobs to a daemon, but don’t want to use some IPC mechanism such as sockets or pipes. Instead, the daemon can sit and watch a submission directory, and jobs can be submitted by dropping a file or directory into the submission directory.
Locking is not taken into account. The watch_directories() function itself doesn’t really need to do locking; if it misses a modification on one pass, it’ll notice it on the next pass. However, if jobs are written directly into a watched directory, the callable object might start running while a job file is only half-written. To solve this, you can use a lockfile; the callable must acquire the lock when it runs, and submitters must acquire the lock when they wish to add a new job. A simpler approach is to rely on the rename() system call being atomic: write the job into a temporary directory that isn’t being watched, and once the file is complete use os.rename() to move it into the submission directory.