一、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监控目录和文件变化的更多相关文章

  1. C# 利用FTP自动下载xml文件后利用 FileSystemWatcher 监控目录下文件变化并自动更新数据库

    using FtpLib; using System; using System.Collections.Generic; using System.ComponentModel; using Sys ...

  2. C#监控指定目录的文件变化的代码

    如下的资料是关于C#监控指定目录的文件变化的代码. FileSystemWatcher watcher = new FileSystemWatcher();watcher.Path = @" ...

  3. python监控tomcat日记文件

    最近写了一个用python监控tomcat日记文件的功能 实现的功能: 监控日记文件中实时过来的记录,统计每分钟各个接口调用次数,统计结果插入oracle #!/usr/bin/python # -* ...

  4. Python获取目录、文件的注意事项

    Python获取指定路径下的子目录和文件有两种方法: os.listdir(dir)和os.walk(dir),前者列出dir目录下的所有直接子目录和文件的名称(均不包含完整路径),如 >> ...

  5. Python 读取目录、文件

    在读文件的时候往往需要遍历文件夹,python的os.path包含了很多文件.文件夹操作的方法.下面列出: os.path.abspath(path) #返回绝对路径 os.path.basename ...

  6. 在windows下实时监控、接受文件变化小工具

    在windows下实时监控文件变化小工具   在测试的时候,我们可能想实时监控系统打出的log信息,在unix系统上我们可以用"tail -f"实现,在windows下一般就无法做 ...

  7. python判断目录或者文件

    1. 判断目录是否存在 'isdir',删除目录时只有该目录为空才可以 'rmdir' import os if(os.path.isdir('D:/Python_workspace/spyder_s ...

  8. shell脚本监控目录下文件被篡改时报警

    思路: 目录下文件被篡改的几种可能: 1.被修改 2.被删除 3.新增文件 md5命令详解 参数: -b 以二进制模式读入文件内容 -t 以文本模式读入文件内容 -c 根据已生成的md5值,对现存文件 ...

  9. python 跨目录访问文件

    1.同级.同目录的文件之间的访问 有这样一个目录结构 假如,in_A.py 这个文件想调用 hello_world.py 中的函数怎么办呢? --->>>  import 只需在 i ...

随机推荐

  1. 20155330 2016-2017-2 《Java程序设计》第八周学习总结

    20155330 2016-2017-2 <Java程序设计>第八周学习总结 教材学习内容总结 学习目标 了解NIO 会使用Channel.Buffer与NIO2 会使用日志API.国际化 ...

  2. POJ 2485 Highways( 最小生成树)

    题目链接 Description The islandnation of Flatopia is perfectly flat. Unfortunately, Flatopia has no publ ...

  3. backup服务器之rsync服务

    backup服务器之rsync服务   rsync是开源的.快速的.多功能的可实现全量及增量的本地或远程数据同步备份的优秀工具.它拥有scp.cp的全量复制功能,同时比scp.cp命令更优秀.更强大. ...

  4. 浅析XSS与XSSI异同

    浅析XSS与XSSI异同 这篇文章主要介绍了XSS与XSSI异同,跨站脚本(XSS)和跨站脚本包含(XSSI)之间的区别是什么?防御方法有什么不同?感兴趣的小伙伴们可以参考一下 Michael Cob ...

  5. 20165227 实验三《敏捷开发与XP实践》实验报告

    2017-2018-4 20165227 实验三<敏捷开发与XP实践>实验报告 实验内容 1.XP基础 2.XP核心实践 3.相关工具 实验要求 1.没有Linux基础的同学建议先学习&l ...

  6. 【黑客免杀攻防】读书笔记18-最终章Anti Rootkit

    1.免杀技巧的遏制 1.1.PE文件 入口点不在第一个区段或在最后一个区段 入口点处代码附近只有一小段代码 入口点在正常范围之外 入口点为一个无效的值,实际入口点为TLS的入口点 区段名重复或者不属于 ...

  7. Linux内核抢占实现机制分析【转】

    Linux内核抢占实现机制分析 转自:http://blog.chinaunix.net/uid-24227137-id-3050754.html [摘要]本文详解了Linux内核抢占实现机制.首先介 ...

  8. aarch64_n3

    ntp-doc-4.2.8p10-1.fc26.noarch.rpm 2017-03-24 02:07 1.2M fedora Mirroring Project ntp-perl-4.2.8p10- ...

  9. C# 调用WSDL接口及方法

    1.首先需要清楚WSDL的引用地址 如:http://XX.XX.4.146:8089/axis/services/getfileno?wsdl 上述地址的构造为 类名getfileno. 2.在.N ...

  10. SQLAlchemy-介绍安装

    一:概述 SQLAlchemy的SQL工具包和对象关系映射是一个全面的工具集,用来处理数据库和Python. 它有几个不同的功能领域,可以单独使用或组合使用. 所示的主要组件,组件依赖关系组织成层: ...