pywin32 py windows 基于ReadDirectoryChangeW做文件变动的监控

首先在windows上映射共享盘

//ip/共享的目录/

import os
import win32file
import win32con
import logging
import requests
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
logfile = os.path.join(os.path.dirname(BASE_DIR, ‘log‘, ‘ta-file.log‘))

logging.basicConfig(
    level=logging.INFO,
    format=‘%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s‘,
	filename=logfile
)


ACTIONS = {
    1: "Created",
    2: "Deleted",
    3: "Updated",
    4: "Renamed from something",
    5: "Renamed to something"
}

FILE_LIST_DIRECTORY = win32con.GENERIC_READ | win32con.GENERIC_WRITE
path_to_watch = "Z:/recv/"
server_ip = ‘192.168.1.66:8888‘

hDir = win32file.CreateFile(
    path_to_watch,
    FILE_LIST_DIRECTORY,
    win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
    None,
    win32con.OPEN_EXISTING,
    win32con.FILE_FLAG_BACKUP_SEMANTICS,
    None
)

if __name__ == ‘__main__‘:
    old_action = ‘‘
    old_filename = ‘‘
    while 1:
        results = win32file.ReadDirectoryChangesW(
            hDir,
            # handle: Handle to the directory to be monitored. This directory must be opened with the FILE_LIST_DIRECTORY access right.
            1024,  # size: Size of the buffer to allocate for the results.
            True,
            # bWatchSubtree: Specifies whether the ReadDirectoryChangesW function will monitor the directory or the directory tree.
            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)
        timestamp = 0
        for action_id, file_path in results:
            full_filename = os.path.join(path_to_watch, file_path)
            action = ACTIONS.get(action_id, "Unknown")

            # 文件创建
            if old_action == ‘Created‘ and action == ‘Updated‘:
                agency, _, file_name = file_path.split(‘\\‘)
                timestamp = int(os.path.getmtime(full_filename))
                logging.info(f‘{file_name} Created‘)
            # 文件更新
            elif old_action == ‘Updated‘ and action == ‘Updated‘ and file_path == old_filename:
                agency, _, file_name = file_path.split(‘\\‘)
                timestamp = int(os.path.getmtime(full_filename))
                logging.info(f‘{file_name} Upadated‘)
            # rint(‘start‘,action,old_action,file_path,old_filename)
            old_action = action
            old_filename = file_path
        if timestamp:
            url = f‘http://{server_ip}/api/dashboard/glafund/ta/fule_record/?file_path={agency}&file_name={file_name}&timestamp={timestamp}‘
            res = requests.get(url)
            logging.info(f‘{file_name} record send success‘)

win api中有对于文件的变动句柄,可以依赖这个事件信号做一些后续处理,在服务器启动相关的接口,接受入参然后写库

pywin32 py windows 基于ReadDirectoryChangeW做文件变动的监控

上一篇:Visual Studio 6.0 在 Windows 10 下崩溃的一种解决方法


下一篇:c#学习心得(4)