How can I “watch” a file for modification / change

2019-01-08 15:48发布

This question already has an answer here:

I would like to invoke my chrome or firefox browser when a file that I specify is modified. How could I "watch" that file to do something when it gets modified?

Programmatically it seems the steps are.. basically set a never ending interval every second or so and cache the initial modification date, then compare the date every second, when it changes invoke X.

标签: python linux
7条回答
成全新的幸福
2楼-- · 2019-01-08 16:13

Install inotify-tools and write a simple shell script to watch a file.

查看更多
小情绪 Triste *
3楼-- · 2019-01-08 16:14

As noted, you can use pyinotify:

E.g.:

import webbrowser
import pyinotify

class ModHandler(pyinotify.ProcessEvent):
    # evt has useful properties, including pathname
    def process_IN_CLOSE_WRITE(self, evt):
            webbrowser.open(URL)

handler = ModHandler()
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, handler)
wdd = wm.add_watch(FILE, pyinotify.IN_CLOSE_WRITE)
notifier.loop()

This is more efficient than polling. The kernel tells you when it does the operation, without you having to constantly ask.

查看更多
姐就是有狂的资本
4楼-- · 2019-01-08 16:19

The other option is to use a checksum. You can use a pattern similar to nose's nosy.py. I use the one from dingus to check my directory for modifications and run the test suite.

查看更多
我命由我不由天
5楼-- · 2019-01-08 16:29

Apparently, watchdog works on both Linux & OSX that can be used to monitor for changes in a directory as well with great example documentation. It also works with python3.x in case you don't want to be forced to use python2.x

查看更多
三岁会撩人
6楼-- · 2019-01-08 16:30

Use FAM to put a monitor on the file.

查看更多
地球回转人心会变
7楼-- · 2019-01-08 16:35

use a quick hash function, a cron job, and off you go!

Also, this looks relevant: http://en.wikipedia.org/wiki/Inotify

查看更多
登录 后发表回答