Python监控目录和文件变化
一、os.listdir
import os, time
path_to_watch = "."
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
time.sleep (10)
after = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in after if not f in before]
removed = [f for f in before if not f in after]
if added: print "Added: ", ", ".join (added)
if removed: print "Removed: ", ", ".join (removed)
before = after
二、FindFirstChangeNotification
import os import win32file
import win32event
import win32con path_to_watch = os.path.abspath (".") #
# FindFirstChangeNotification sets up a handle for watching
# file changes. The first parameter is the path to be
# watched; the second is a boolean indicating whether the
# directories underneath the one specified are to be watched;
# the third is a list of flags as to what kind of changes to
# watch for. We're just looking at file additions / deletions.
#
change_handle = win32file.FindFirstChangeNotification (
path_to_watch,
0,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME
) #
# Loop forever, listing any file changes. The WaitFor... will
# time out every half a second allowing for keyboard interrupts
# to terminate the loop.
#
try: old_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
while 1:
result = win32event.WaitForSingleObject (change_handle, 500) #
# If the WaitFor... returned because of a notification (as
# opposed to timing out or some error) then look for the
# changes in the directory contents.
#
if result == win32con.WAIT_OBJECT_0:
new_path_contents = dict ([(f, None) for f in os.listdir (path_to_watch)])
added = [f for f in new_path_contents if not f in old_path_contents]
deleted = [f for f in old_path_contents if not f in new_path_contents]
if added: print "Added: ", ", ".join (added)
if deleted: print "Deleted: ", ", ".join (deleted) old_path_contents = new_path_contents
win32file.FindNextChangeNotification (change_handle) finally:
win32file.FindCloseChangeNotification (change_handle)
三、ReadDirectoryChanges
#coding:utf8
#author:lcamry
import os import win32file
import win32con ACTIONS = {
1 : "Created",
2 : "Deleted",
3 : "Updated",
4 : "Renamed from something",
5 : "Renamed to something"
}
# Thanks to Claudio Grondi for the correct set of numbers
FILE_LIST_DIRECTORY = 0x0001 path_to_watch = "."
hDir = win32file.CreateFile (
path_to_watch,
FILE_LIST_DIRECTORY,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE | win32con.FILE_SHARE_DELETE,
None,
win32con.OPEN_EXISTING,
win32con.FILE_FLAG_BACKUP_SEMANTICS,
None
)
while 1:
#
# ReadDirectoryChangesW takes a previously-created
# handle to a directory, a buffer size for results,
# a flag to indicate whether to watch subtrees and
# a filter of what changes to notify.
#
# NB Tim Juchcinski reports that he needed to up
# the buffer size to be sure of picking up all
# events when a large number of files were
# deleted at once.
#
results = win32file.ReadDirectoryChangesW (
hDir,
1024,
True,
win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
win32con.FILE_NOTIFY_CHANGE_SIZE |
win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
win32con.FILE_NOTIFY_CHANGE_SECURITY,
None,
None
)
for action, file in results:
full_filename = os.path.join (path_to_watch, file)
print full_filename, ACTIONS.get (action, "Unknown")
四、watchdog
#coding:utf8
#author:lcamry
from watchdog.observers import Observer
from watchdog.events import *
import time class FileEventHandler(FileSystemEventHandler):
def __init__(self):
FileSystemEventHandler.__init__(self) def on_moved(self, event):
if event.is_directory:
print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))
else:
print("file moved from {0} to {1}".format(event.src_path,event.dest_path)) def on_created(self, event):
if event.is_directory:
print("directory created:{0}".format(event.src_path))
else:
print("file created:{0}".format(event.src_path)) def on_deleted(self, event):
if event.is_directory:
print("directory deleted:{0}".format(event.src_path))
else:
print("file deleted:{0}".format(event.src_path)) def on_modified(self, event):
if event.is_directory:
print("directory modified:{0}".format(event.src_path))
else:
print("file modified:{0}".format(event.src_path)) if __name__ == "__main__":
observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler,"d:/dcm",True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
五、linux下pyinotify
#coding:utf8
#author:lcamry
import os
import pyinotify
from functions import * WATCH_PATH = '' #监控目录 if not WATCH_PATH:
wlog('Error',"The WATCH_PATH setting MUST be set.")
sys.exit()
else:
if os.path.exists(WATCH_PATH):
wlog('Watch status','Found watch path: path=%s.' % (WATCH_PATH))
else:
wlog('Error','The watch path NOT exists, watching stop now: path=%s.' % (WATCH_PATH))
sys.exit() class OnIOHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
wlog('Action',"create file: %s " % os.path.join(event.path,event.name)) def process_IN_DELETE(self, event):
wlog('Action',"delete file: %s " % os.path.join(event.path,event.name)) def process_IN_MODIFY(self, event):
wlog('Action',"modify file: %s " % os.path.join(event.path,event.name)) def auto_compile(path = '.'):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_CREATE | pyinotify.IN_DELETE | pyinotify.IN_MODIFY
notifier = pyinotify.ThreadedNotifier(wm, OnIOHandler())
notifier.start()
wm.add_watch(path, mask,rec = True,auto_add = True)
wlog('Start Watch','Start monitoring %s' % path)
while True:
try:
notifier.process_events()
if notifier.check_events():
notifier.read_events()
except KeyboardInterrupt:
notifier.stop()
break if __name__ == "__main__":
auto_compile(WATCH_PATH)
Python监控目录和文件变化的更多相关文章
- C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库
		
using FtpLib; using System; using System.Collections.Generic; using System.ComponentModel; using Sys ...
 - C#监控指定目录的文件变化的代码
		
如下的资料是关于C#监控指定目录的文件变化的代码. FileSystemWatcher watcher = new FileSystemWatcher();watcher.Path = @" ...
 - python监控tomcat日记文件
		
最近写了一个用python监控tomcat日记文件的功能 实现的功能: 监控日记文件中实时过来的记录,统计每分钟各个接口调用次数,统计结果插入oracle #!/usr/bin/python # -* ...
 - Python获取目录、文件的注意事项
		
Python获取指定路径下的子目录和文件有两种方法: os.listdir(dir)和os.walk(dir),前者列出dir目录下的所有直接子目录和文件的名称(均不包含完整路径),如 >> ...
 - Python 读取目录、文件
		
在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...
 - 在windows下实时监控、接受文件变化小工具
		
在windows下实时监控文件变化小工具 在测试的时候,我们可能想实时监控系统打出的log信息,在unix系统上我们可以用"tail -f"实现,在windows下一般就无法做 ...
 - python判断目录或者文件
		
1. 判断目录是否存在 'isdir',删除目录时只有该目录为空才可以 'rmdir' import os if(os.path.isdir('D:/Python_workspace/spyder_s ...
 - shell脚本监控目录下文件被篡改时报警
		
思路: 目录下文件被篡改的几种可能: 1.被修改 2.被删除 3.新增文件 md5命令详解 参数: -b 以二进制模式读入文件内容 -t 以文本模式读入文件内容 -c 根据已生成的md5值,对现存文件 ...
 - python 跨目录访问文件
		
1.同级.同目录的文件之间的访问 有这样一个目录结构 假如,in_A.py 这个文件想调用 hello_world.py 中的函数怎么办呢? --->>> import 只需在 i ...
 
随机推荐
- [转载]WCF和ASP.NET Web API在应用上的选择
			
http://www.cnblogs.com/shanyou/archive/2012/09/26/2704814.html http://msdn.microsoft.com/en-us/libra ...
 - 【转】Graphics.DrawImage 方法 IntPtr 结构 GDI 句柄 知识收集
			
Graphics.DrawImage 方法 在指定的位置使用原始物理大小绘制指定的 Image. 命名空间:System.Drawing 程序集:System.Drawing(在 system.dra ...
 - 【译】第十三篇 Integration Services:SSIS变量
			
本篇文章是Integration Services系列的第十三篇,详细内容请参考原文. 简介在前一篇我们结合了之前所学的冒泡.日志记录.父子模式创建一个自定义的SSIS包日志记录模式.在这一篇,我们将 ...
 - cdn_一些常用的cdn地址
			
https://code.jquery.com/jquery-3.3.1.jshttps://cdn.bootcss.com/jquery/2.1.4/jquery.min.js https://cd ...
 - PyText
			
Facebook开源了自家工程师们一直在用的NLP建模框架PyText.这个框架,每天要为Facebook旗下各种应用处理超过10亿次NLP任务,Facebook AI的工业级NLP开源框架.(简化部 ...
 - python并发爬虫利器tomorrow(一)
			
tomorrow是我最近在用的一个爬虫利器,该模块属于第三方的一个模块,使用起来非常的方便,只需要用其中的threads方法作为装饰器去修饰一个普通的函数,既可以达到并发的效果,本篇将用实例来展示to ...
 - PHP的数据库连接mysqli遍历示例
			
$mysqli = mysqli_init(); $mysqli->options(MYSQLI_OPT_CONNECT_TIMEOUT, 2);//设置超时时间,以秒为单位的连接超时时间 $m ...
 - Jenkins忘记用户名密码
			
一.进入C盘.jenkins配置文件中找到config.xml 需要删除一下内容: <useSecurity>true</useSecurity> <authorizat ...
 - sed实例收集
			
url:http://blog.csdn.net/hepeng597/article/details/7852468 一.元字符集 1)^锚定行的开始 如:/^sed/匹配所有以sed开头的行. ...
 - Flask:初次使用Blueprints
			
Windows 10家庭中文版,Python 3.6.4,Flask 1.0.2,Eclipse Oxygen.1a Release (4.7.1a),PyDev 6.3.2 本文为记录自己第一次使用 ...