天天看点

python文件监控-watchdog

背景说明:

实际做项目时候,往往需要适时监控某一个文件夹,推荐使用watchdog。

# -*- coding: utf-8 -*-
import os ,shutil,time
from watchdog.observers import Observer
from watchdog.events import *
import configparser   
###################监控文件夹下文件的变化并复制到另一目录后删除###################
class FileEventHandler(FileSystemEventHandler):
    def __init__(self):
        FileSystemEventHandler.__init__(self)

    def on_created(self, event):
        if event.is_directory:
            print("directory created:{0}".format(event.src_path))
        else:
            filename= format(event.src_path)
            print(filename,type(filename))
            time.sleep(0.5)
            if os.path.exists(filename):
                #copyCommand = 'copy %s %s' % (filename, fn)
                copyCommand = os.system('xcopy "'+filename+'" D:\MonitoringSystem\video_source')
                time.sleep(0.5)
                if copyCommand == 0:
                    print('copy successed!')                           
                else:
                    print('copy failed!',copyCommand)
                        
if __name__ == "__main__":
    global fn
    config = configparser.ConfigParser()
    config.read('Config.ini',encoding='utf-8')
    watchpath = config.get('watch config', 'watchpath')
    fn = config.get('watch config', 'videopath')
    root_dir= watchpath 
    observer = Observer()
    event_handler = FileEventHandler()
    observer.schedule(event_handler,root_dir,True)    
    observer.start()
    print('视频监控程序运行中,请不要关闭......')
    print("*"*60)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()
           

说明:

有时候我们在用watchdog监控文件夹并复制文件到别的文件夹的时候,因为文件夹名字中有空格往往会导致赋值失败,这时候需要对字符串进行处理。推荐一个参考程序:

import os
fn = "D:\Record"
aa="E:\J04_2020.03.19 00_20_02_manual.txt"
try:
    #bb=os.system('xcopy "E:\J04_2020.03.19 00_20_02_manual.txt" D:\Record')
    bb=os.system('xcopy "'+aa+'" D:\Record')
    print('复制成功!',bb)
except:
    print('文件名不正确!')
finally:
    print('无奈啊!')