Watchdog脚本只能检测由我自己直接创建的文件(与目标软件相反)

2024-09-27 23:19:06 发布

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

我编写了一个看门狗脚本,用于检测新创建的具有特定扩展名的文件,并对其执行操作(重命名、为文件创建新目录等)。这是使用watchdog库创建的:使用on_created函数创建了一个处理程序(我也尝试了on_modified)。脚本运行良好,但仅当我通过复制现有文件或自己创建文件(从IDE并添加目标扩展名)来创建文件时,脚本才会运行。从应用程序创建文件时(例如保存、另存为等),由于某些原因,不会引发事件,因此代码不会执行。该脚本最初是为了检测“.zpr”文件(来自3d软件Zbrush)并对其进行操作而编写的,但我已经用其他应用程序(如Adobe Illustrator-.ai文件)进行了测试,以测试这是否与该特定应用程序保存其文件的方式有关,而不是。任何帮助都将不胜感激。谢谢

我的代码:

import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import os
from pathlib import Path



desktop_path = Path("/Users/me/Desktop")
project_dir_path = Path("/Users/me/Documents/Zbrush/Projects")

class Watcher:

    def __init__(self, directory=desktop_path, handler=FileSystemEventHandler()):
        self.observer = Observer()
        self.handler = handler
        self.directory = directory

    def run(self):
        self.observer.schedule(
            self.handler, self.directory, recursive=True)
        self.observer.start()
        print("\nWatcher Running in {}/\n".format(self.directory))
        try:
            while True:
                time.sleep(1)
        except:
            self.observer.stop()
        self.observer.join()
        print("\nWatcher Terminated\n")


class MyHandlers(FileSystemEventHandler): #probably where the problem is

    def on_created(self, event):

        if event.src_path[-4:] == ".zpr" or event.src_path[-4] == ".ZPR":
            new_zfile_name = event.src_path.split("/")
            new_zfile_name = new_zfile_name[-1]
            new_zfile_name_name, new_zfile_name_ext = os.path.splitext(new_zfile_name)
            os.chdir("/Users/me/Documents/Zbrush/Projects")
            for directory in (os.listdir(os.getcwd())):

                if directory == new_zfile_name_name:

                    os.chdir(f"/Users/me/Documents/Zbrush/Projects/{directory}")
                    for existing_zfile in os.listdir(os.getcwd()):
                        if existing_zfile == new_zfile_name:
                            os.remove(existing_zfile)
                            os.rename(f"/Users/me/Desktop/{new_zfile_name}",
                                      f"/Users/me/Documents/Zbrush/Projects/{directory}/{new_zfile_name}")
                            print(f"The file {new_zfile_name} has been moved to the new location {project_dir_path / directory}")


                elif not os.path.isfile(project_dir_path / new_zfile_name_name):
                    os.chdir(project_dir_path)
                    os.makedirs(new_zfile_name_name, exist_ok=True)
                    os.rename(os.path.join(f"/Users/me/Desktop/{new_zfile_name}"),
                              os.path.join(f"/Users/me/Documents/Zbrush/Projects/{new_zfile_name_name}/{new_zfile_name}"))

                    break



    if __name__ == "__main__":
        w = Watcher(desktop_path, MyHandlers())
        w.run()

Tags: 文件pathnameimportselfnewosusers

热门问题