首页 > 解决方案 > Python 中的看门狗查找文件系统更改不起作用(冻结)

问题描述

我正在编写一个 Python 脚本来监视一个文件夹,以检查是否将新的 *.JPG 文件添加到该文件夹​​中,然后执行一些任务。该代码正在运行,但在启动一段时间后,它似乎被冻结并停止工作,即使将新文件添加到文件夹中也是如此。

这是代码:

# -*- encoding: iso-8859-1 -*-
import time
import os
import flickrapi
import shutil
from PIL import Image
from PIL.ExifTags import TAGS
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler

if __name__ == "__main__":
    patterns = ["*.jpg"]
    ignore_patterns = None
    ignore_directories = False
    case_sensitive = False
    my_event_handler = PatternMatchingEventHandler(patterns, ignore_patterns, ignore_directories, case_sensitive)

def get_exif(img):
    ''' Extract Exif data from image '''

def copyright(img):
    # get the path of img and create an output filename
    tail = os.path.split(img)[1]
    filename = 'wtmk_' + tail[:-3] + 'png'

    #open the base image and get it's dimensions
    while True:
        try:
            # read file
            base_image = Image.open(img)
            bw, bh = base_image.size
            bw2 = bw // 2
            break
        except IOError:
            time.sleep(5)
            
       ''' Add watermark to image '''
    
    return waterMarkedImage

def on_created(event):
    # Add the watermark
    file = copyright(event.src_path)

    # extract EXIF data
    exifdata = get_exif(event.src_path)
 
    ''' Send the image to FLICKR '''

# Create and start the observer
my_event_handler.on_created = on_created

path = "c:\\temp"
go_recursively = False
my_observer = Observer()
my_observer.schedule(my_event_handler, path, recursive=go_recursively)
my_observer.start()

try:
    while True:
            time.sleep(5)
except KeyboardInterrupt:
        my_observer.stop()
        my_observer.join()

我在 Windows 10 机器上使用 Python 3.8 运行上述代码。任何帮助都是极好的!

马西奥

标签: python-3.xpython-watchdog

解决方案


推荐阅读