Python 如何“监视”文件以进行修改/更改?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3274334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:21:37  来源:igfitidea点击:

How can I "watch" a file for modification / change?

pythonlinux

提问by meder omuraliev

I would like to invoke my chromeor firefoxbrowser when a file that I specify is modified. How could I "watch" that file to do something when it gets modified?

当我指定的文件被修改时,我想调用我的chromefirefox浏览器。当它被修改时,我怎么能“观察”该文件以执行某些操作?

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.

从编程上看,这些步骤似乎是......基本上每秒设置一个永无止境的间隔并缓存初始修改日期,然后每秒比较日期,当它更改调用 X 时。

采纳答案by Matthew Flaschen

As noted, you can use pyinotify:

如前所述,您可以使用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.

这比轮询更有效。内核会在执行操作时告诉您,而无需您不断询问。

回答by Sam Dolan

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

另一种选择是使用校验和。您可以使用类似于nose 的nosy.py 的模式。我使用来自dingus的一个来检查我的目录是否有修改并运行测试套件。

回答by gtrak

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

使用快速散列函数、cron 作业,然后就可以了!

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

此外,这看起来很相关:http: //en.wikipedia.org/wiki/Inotify

回答by Dr. Snoopy

The Linux Kernel has a file monitoring API called inotify. A python binding is pyinotify.

Linux 内核有一个名为 inotify 的文件监控 API。python 绑定是pyinotify

With it, you can build what you want.

有了它,您可以构建您想要的东西。

回答by Ignacio Vazquez-Abrams

Use FAMto put a monitor on the file.

使用FAM在文件上放置监视器。

回答by nwmcsween

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

安装 inotify-tools 并编写一个简单的 shell 脚本来监视文件。

回答by jamescampbell

Apparently, watchdogworks 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

显然,看门狗适用于 Linux 和 OSX,可用于监视目录中的更改以及很好的示例文档。如果您不想被迫使用 python2.x,它也适用于 python3.x