天天看點

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('無奈啊!')