使用 Python 监控文件系统事件,无需其他低级库
例如,我需要捕获 Linux 操作系统上某个目录上的删除和添加文件事件。我找到了像 inotify 和 python 包装器这样的库,但是如果我想使用清晰的 python 代码,我应该每秒观察 os.listdir(path) 输出,还是有一些方法可以完成这样的任务?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
来源:http://code.activestate.com/ Recipes/215418-watching-a-directory-tree-on-unix/
watch_directories() 函数采用路径列表和可调用对象,然后重复遍历目录树以这些路径为根,监视被删除或修改时间更改的文件。然后向可调用对象传递两个列表,其中包含已更改的文件和已删除的文件。
当您想要某种方式将作业发送到守护程序,但又不想使用某些 IPC 机制(例如套接字或管道)时,此配方很有用。相反,守护进程可以坐下来监视提交目录,并且可以通过将文件或目录放入提交目录来提交作业。
不考虑锁定。 watch_directories() 函数本身并不需要进行锁定;如果它在一次传递中错过了修改,它会在下一次传递时注意到它。但是,如果作业直接写入监视目录,则可调用对象可能会在作业文件仅写入一半时开始运行。为了解决这个问题,你可以使用锁文件;可调用对象在运行时必须获取锁,提交者在希望添加新作业时也必须获取锁。一种更简单的方法是依赖 rename() 系统调用的原子性:将作业写入未监视的临时目录,文件完成后使用 os.rename() 将其移动到提交目录中。
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.