Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I watch a file for changes?

I have a log file being written by another process which I want to watch for changes. Each time a change occurs I'd like to read the new data in to do some processing on it.

What's the best way to do this? I was hoping there'd be some sort of hook from the PyWin32 library. I've found the win32file.FindNextChangeNotification function but have no idea how to ask it to watch a specific file.

If anyone's done anything like this I'd be really grateful to hear how...

[Edit] I should have mentioned that I was after a solution that doesn't require polling.

[Edit] Curses! It seems this doesn't work over a mapped network drive. I'm guessing windows doesn't 'hear' any updates to the file the way it does on a local disk.

like image 479
Jon Cage Avatar asked Oct 08 '08 11:10

Jon Cage


People also ask

How can you watch a file for changes and log the filename after each change?

You can maybe use the fs. appendFile(); function so that when something is being written into the file you emit an event to something else that "logs" your new data that is being written. This will allow you to watch a file for changes.

What is a file watcher?

File Watcher is an IntelliJ IDEA tool that allows you to automatically run a command-line tool like compilers, formatters, or linters when you change or save a file in the IDE.

How will you monitor file change in Linux?

In Linux, the default monitor is inotify. By default, fswatch will keep monitoring the file changes until you manually stop it by invoking CTRL+C keys. This command will exit just after the first set of events is received. fswatch will monitor changes in all files/folders in the specified path.


2 Answers

Did you try using 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...

like image 140
simao Avatar answered Oct 24 '22 19:10

simao


If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:

os.stat(filename).st_mtime 

(Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)

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... 
like image 41
Deestan Avatar answered Oct 24 '22 20:10

Deestan