本文介绍了用python检测新的或修改的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我试图寻找一个脚本,用来查找一个新的文件是否创建了一个目录或者一个已经存在的文件在一个目录中被修改。会做到这一点(最好在Python或bash中),但总结起来。我的环境是Python 2.6的Python



解决方案 c>它是GLib的文件系统部分(在GLib的python绑定中)

$ $ p $ $ $ $ c $ import $ $ $ $ $ $ $ $ $ $如果(evi_type in(gio.FILE_MONITOR_EVENT_CREATED,
gio.FILE_MONITOR_EVENT_DELETED)):
printChanged:,file1,file2,evt_type

gfile = gio.File(。)
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE,无)
monitor.connect(changed,directory_changed)

但是,您的程序必须运行一个GLib主循环才能到达事件。一个快速测试的方法是使用:

pre $ $ $ c $ import b
ml = glib.MainLoop()
ml.run()

GLib是一个非常适合应用程序的高级库。您不必关心它用于文件监视的底层系统。






我现在看到你使用Fedora核心2.真正的版本2?在GLib中使用GIO可能太老了。 Pyinotify已被提及可能是一个更好的解决方案,虽然不太便携。

I'm trying to detect when a new file is created a directory or when an existing file is modified in a directory.

I tried searching for a script that would do this (preferably in python or bash) but came up short. My environment is linux with Python 2.6

Related Question

解决方案

You can use gio which is the Filesystem part of GLib (In GLib's python bindings)

import gio

def directory_changed(monitor, file1, file2, evt_type):
   if (evt_type in (gio.FILE_MONITOR_EVENT_CREATED,
       gio.FILE_MONITOR_EVENT_DELETED)):
       print "Changed:", file1, file2, evt_type

gfile = gio.File(".")
monitor = gfile.monitor_directory(gio.FILE_MONITOR_NONE, None)
monitor.connect("changed", directory_changed)

however, your program must be running a GLib mainloop for the events to arrive. One quick way to test that is by using:

import glib
ml = glib.MainLoop()
ml.run()

GLib is a high-level library which is well suited for Applications. You don't have to care about which underlying system it uses for the file monitoring.


I now see you use Fedora Core 2. Really version 2? That might be too old to use GIO in GLib. Pyinotify that has been mentioned might be a better solution, although less portable.

这篇关于用python检测新的或修改的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-14 11:44