如何在python中获取文件关闭事件 [英] How to get a file close event in python

查看:172
本文介绍了如何在python中获取文件关闭事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Windows 7 64位计算机上使用python 2.7.

Using python 2.7 on windows 7 64 bit machine.

如何获取文件关闭事件:

How to get a file close event:

  1. 在新的文件打开器进程中打开文件时(例如记事本,写字板,每次在新的写字板过程中都会打开文件)
  2. 在文件打开器的标签页中打开文件时(例如notepad ++,它将在新标签页中打开所有文件,但仅运行一个单独的notepad ++进程)

那么,在上述情况下如何获取文件关闭事件?是否可以通过通用代码实现上述情况?我正在处理不同的文件类型

So, how to get file close event in above cases? Is it possible to achieve above cases through a common code? I am dealing with different file types

推荐答案

对于* nix系统,这已被证明是一项非常简单的任务,但是在Windows上,获取文件关闭事件并非易事.请阅读以下按操作系统分组的常用方法摘要.

This has proven to be a very easy task for *nix systems, but on Windows, getting a file close event is not a simple task. Read below the summary of common methods grouped by OS'es.

在Linux上,可以轻松且详细地监视文件系统更改.最好的工具是称为inotify的内核功能,并且有一个使用它的Python实现称为Pynotify.

On Linux, the filesystem changes can be easily monitored, and in great detail. The best tool for this is the kernel feature called inotify, and there is a Python implementation that uses it, called Pynotify.

  • Pyinotify

    Pyinotify是用于监视文件系统更改的Python模块. Pyinotify依赖于称为事件驱动的通知程序inotify的Linux内核功能(合并在内核2.6.13中).它的通知通过三个系统调用从内核空间导出到用户空间. Pyinotify绑定这些系统调用,并在它们之上提供一个实现,从而提供一种通用且抽象的方式来操纵这些功能.

  • Pyinotify

    Pyinotify is a Python module for monitoring filesystems changes. Pyinotify relies on a Linux Kernel feature (merged in kernel 2.6.13) called inotify, which is an event-driven notifier. Its notifications are exported from kernel space to user space through three system calls. Pyinotify binds these system calls and provides an implementation on top of them offering a generic and abstract way to manipulate those functionalities.

此处,您可以找到可以用Pynotify监视的事件列表.

Here you can find the list of the events that can be monitored with Pynotify.

用法示例:

导入pyinotify

import pyinotify

class EventHandler(pyinotify.ProcessEvent):
    def process_IN_CLOSE_NOWRITE(self, event):
        print "File was closed without writing: " + event.pathname
    def process_IN_CLOSE_WRITE(self, event):
        print "File was closed with writing: " + event.pathname

def watch(filename):
    wm = pyinotify.WatchManager()
    mask = pyinotify.IN_CLOSE_NOWRITE | pyinotify.IN_CLOSE_WRITE
    wm.add_watch(filename, mask)

    eh = EventHandler()
    notifier = pyinotify.Notifier(wm, eh)
    notifier.loop()

if __name__ == '__main__':
    watch('/path/to/file')

Windows的情况比Linux的情况复杂得多.大多数库都依赖ReadDirectoryChanges API,该API受限制并且无法检测到更详细的信息,例如文件关闭事件.但是,还有其他检测此类事件的方法,请继续阅读以了解更多信息.

Situation for Windows is quite a bit more complex than for Linux. Most libraries rely on ReadDirectoryChanges API which is restricted and can't detect finer details like file close event. There are however other methods for detecting such events, so read on to find out more.

  • 观察者

    注意:观察器的最新更新时间为2011年2月,因此跳过此监视程序可能很安全.

  • Watcher

    Note: Watcher has been last updated in February 2011, so its probably safe to skip this one.

Watcher是低级C扩展,用于在Windows系统上使用ReadDirectoryChangesW API接收文件系统更新.该软件包还包括一个高级接口,以模拟大多数.NET FileSystemWatcher API.
使用Watcher检测文件关闭事件最接近的方法是监视FILE_NOTIFY_CHANGE_LAST_WRITE和/或FILE_NOTIFY_CHANGE_LAST_ACCESS事件.

Watcher is a low-level C extension for receiving file system updates using the ReadDirectoryChangesW API on Windows systems. The package also includes a high-level interface to emulate most of the .NET FileSystemWatcher API.
The closest one can get to detecting file close events with Watcher is to monitor the FILE_NOTIFY_CHANGE_LAST_WRITE and/or FILE_NOTIFY_CHANGE_LAST_ACCESS events.

用法示例:

import watcher
w = watcher.Watcher(dir, callback)
w.flags = watcher.FILE_NOTIFY_CHANGE_LAST_WRITE
w.start()

  • 看门狗

    Python API和Shell实用程序,用于监视文件系统事件.易于安装:$ pip install watchdog.有关更多信息,请访问文档.
    Windows上的Watchdog依赖ReadDirectoryChangesW API,与Watcher和其他依赖同一API的库一样,它也带来了警告.

  • Watchdog

    Python API and shell utilities to monitor file system events. Easy install: $ pip install watchdog. For more info visit the documentation.
    Watchdog on Windows relies on the ReadDirectoryChangesW API, which brings its caveats as with Watcher and other libraries relying on the same API.

    Linux watch命令的python近克隆.可以告诉pywatch.watcher.Watcher类观看一组文件,并指定一组命令以在这些文件中的任何一个更改时运行.由于它依赖于轮询 stat的st_mtime ,因此它只能监视文件更改事件.

    A python near-clone of the Linux watch command. The pywatch.watcher.Watcher class can be told to watch a set of files, and given a set of commands to run whenever any of those files change. It can only monitor the file changed event, since it relies on polling the stat's st_mtime.

    • NTFS USN日志

      "NTFS USN(更新序列号)日志"是NTFS的一项功能,它保留对卷所做的更改的记录.之所以将其列为 Bonus 的原因是,与其他条目不同,它不是特定的库,而是NTFS系统上现有的功能.因此,如果您正在使用其他Windows文件系统(例如FAT,ReFS等),则此方法不适用.
      系统将对卷所做的所有更改记录在USN Journal文件中的工作方式,每个卷都有其自己的实例.更改日志中的每个记录都包含USN,文件名以及有关更改内容的信息.

    • NTFS USN Journal

      The NTFS USN (Update Sequence Number) Journal is a feature of NTFS which maintains a record of changes made to the volume. The reason it is listed as a Bonus is because unlike the other entries, it is not a specific library, but rather a feature existing on NTFS system. So if you are using other Windows filesystems (like FAT, ReFS, etc..) this does not apply.
      The way it works it that the system records all changes made to the volume in the USN Journal file, with each volume having its own instance. Each record in the Change Journal contains the USN, the name of the file, and information about what the change was.

    此方法之所以引起人们的关注,主要原因在于,与其他大多数方法不同,该方法提供了一种检测文件关闭事件的方法,该事件定义为 USN_REASON_CLOSE .可以在此 MSDN文章.有关USN日记的完整文档,请访问以下 MSDN页面.

    The main reason this method is interesting for this question is that, unlike most of the other methods, this one provides a way to detect a file close event, defined as USN_REASON_CLOSE. More information with a complete list of events can be found in this MSDN article. For a complete documentation about USN Journaling, visit this MSDN page.

    有多种方法可以从Python访问USN期刊,但唯一成熟的选择似乎是

    There are multiple ways to access the USN Journal from Python, but the only mature option seems to be the ntfsjournal module.

    文件系统过滤器驱动程序是可选驱动程序,可以为 或修改文件系统的行为.文件系统过滤器驱动程序 是作为Windows执行程序的一部分运行的内核模式组件. 文件系统筛选器驱动程序可以筛选一个或多个的I/O操作 文件系统或文件系统卷.视乎性质 驱动程序,过滤器可能意味着记录,观察,修改甚至阻止.典型的 文件系统过滤器驱动程序的应用程序包括防病毒软件 实用程序,加密程序和分层存储管理 系统.

    A file system filter driver is an optional driver that adds value to or modifies the behavior of a file system. A file system filter driver is a kernel-mode component that runs as part of the Windows executive. A file system filter driver can filter I/O operations for one or more file systems or file system volumes. Depending on the nature of the driver, filter can mean log, observe, modify, or even prevent. Typical applications for file system filter drivers include antivirus utilities, encryption programs, and hierarchical storage management systems.

    实现文件系统过滤器驱动程序不是一件容易的事,但是对于想尝试一下的人来说,

    It is not an easy task to implement a file system filter driver, but for someone who would like to give it a try, there is a good introduction tutorial on CodeProject.

    P.S.检查 @ ixe013的答案以获取有关此方法的其他信息.

    P.S. Check @ixe013's answer for some additional info about this method.

    • Qt的QFileSystemWatcher

      QFileSystemWatcher类提供了一个接口,用于监视文件和目录的修改.此类在Qt 4.2中引入.
      不幸的是,它的功能相当有限,因为它只能检测文件何时被修改,重命名或删除,以及何时将新文件添加到目录中.

    • Qt's QFileSystemWatcher

      The QFileSystemWatcher class provides an interface for monitoring files and directories for modifications. This class was introduced in Qt 4.2.
      Unfortunately, its functionality is fairly limited, as it can only detect when a file has been modified, renamed or deleted, and when a new file was added to a directory.

    用法示例:

    import sys
    from PyQt4 import QtCore
    
    def directory_changed(path):
        print('Directory Changed: %s' % path)
    
    def file_changed(path):
        print('File Changed: %s' % path)
    
    app = QtCore.QCoreApplication(sys.argv)
    
    paths = ['/path/to/file']
    fs_watcher = QtCore.QFileSystemWatcher(paths)
    fs_watcher.directoryChanged.connect(directory_changed)
    fs_watcher.fileChanged.connect(file_changed)
    
    app.exec_()
    

  • 这篇关于如何在python中获取文件关闭事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆