如何监视文件的更改?

2024-04-26 05:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个日志文件正在由另一个进程写入,我希望监视其更改。每次发生更改时,我都想读入新数据以对其进行一些处理。

最好的方法是什么?我希望PyWin32库里会有某种钩子。我找到了win32file.FindNextChangeNotification函数,但不知道如何要求它监视特定文件。

如果有人做过这样的事,我会非常感激听到。。。

[编辑]我应该提到我正在寻找一个不需要轮询的解决方案。

[编辑]诅咒!似乎这在映射的网络驱动器上不起作用。我猜windows不会像在本地磁盘上那样“听到”文件的任何更新。


Tags: 文件数据方法函数网络编辑进程windows
3条回答

你试过用Watchdog吗?

Python API library and shell utilities to monitor file system events.

Directory monitoring made easy with

  • A cross-platform API.
  • A shell tool to run commands in response to directory changes.

Get started quickly with a simple example in Quickstart...

如果投票对你来说足够好的话,我只会观察“修改时间”文件状态是否改变。阅读:

os.stat(filename).st_mtime

(还要注意,Windows本机更改事件解决方案并非在所有情况下都能工作,例如在网络驱动器上。)

import os

class Monkey(object):
    def __init__(self):
        self._cached_stamp = 0
        self.filename = '/path/to/file'

    def ook(self):
        stamp = os.stat(self.filename).st_mtime
        if stamp != self._cached_stamp:
            self._cached_stamp = stamp
            # File has changed, so do something...

你已经看过http://timgolden.me.uk/python/win32_how_do_i/watch_directory_for_changes.html上的文档了吗?如果只需要在Windows下工作,那么第二个示例似乎正是您想要的(如果您将目录的路径与要监视的文件之一交换)。

否则,轮询可能是唯一真正独立于平台的选项。

注意:我没有尝试过这些解决方案。

相关问题 更多 >