python监视程序在几分钟后停止捕获事件

2022-05-21 07:47:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行一个python脚本,使用watchdog监视并记录特定文件夹中的任何文件更改。脚本运行约12小时,但在运行并记录文件更改约15分钟后,脚本停止捕获任何事件,即使文件夹中有新文件被删除

我做了检查,python脚本仍在后台运行

有人能告诉我为什么吗

import os
import logging
import time
import datetime
from watchdog.observers import Observer 
from watchdog.events import FileSystemEventHandler

#Functions for event handler
def on_created(event):
    
    #Checking file size
    file_size = -1
    while file_size != os.path.getsize(event.src_path):
        file_size = os.path.getsize(event.src_path)
        time.sleep(5)
    logging.info("File_created=" + event.src_path + "; file_size=" + str(file_size))
    
def on_modified(event):
    logging.info("File_modified=" + event.src_path + "; file_size=" + str(file_size))

def on_deleted(event):
    logging.info("File_deleted=" + event.src_path)

def on_moved(event):
    logging.info("File_moved=" + event.src_path)

def file_checker():

    logdate = datetime.datetime.now().strftime('%Y%m%d')
    logging.basicConfig(level=logging.INFO, filename='file_monitor_'+logdate+'.log', format='%(asctime)s %(levelname)s : %(message)s',datefmt='%Y-%m-%d %H:%M:%S')
    
    
    #Set folder to monitor
    path = '/data/files/current'
    
    # Initialize Filesystem event handler     
    event_handler = FileSystemEventHandler()
    
    # Call the event handler functions
    event_handler.on_created = on_created
    #event_handler.on_modified = on_modified
    event_handler.on_deleted = on_deleted
    event_handler.on_moved = on_moved
    
    # Initialize Observer 
    observer = Observer() 
    observer.schedule(event_handler, path, recursive=False) 
  
    # Start the observer 
    observer.start() 
    try:
        logging.info("Monitoring started")
        while True: 
            # Set the thread sleep time 
            time.sleep(2) 
    except KeyboardInterrupt:
        observer.stop()
        logging.info("Monitoring stopped")
    observer.join() 

if __name__ == '__main__':
    file_checker()

Tags: pathimportinfosrc脚本eventsizetimeonloggingdefobserverfilehandlercreated