Watchdog简单使用

对文件夹进行监听,使用on_created、on_moved等方法对文件进行处理。

ps: watchdog监听文件,一堆图片进来时,是按序执行

class FileMonitorHandler(FileSystemEventHandler):
    def on_created(self, event):
        file_path = event.src_path
        print('Add new photo: ', file_path)
        # 给图片添加读写执行权限
        os.system("icacls {} /grant administrator:F".format(file_path))
        if file_path.split('.')[-1] in FILE_TYPE:
            uid = getuid(file_path)
            r = requests.post('http://localhost:8001/inspect',
                              data={'pic': file_path})
​
    def on_moved(self, event):
        print("move file: ", event.src_path)
​
​
if __name__ == "__main__":
    path = filename
    event_handler = FileMonitorHandler()
    observer = Observer()
    observer.schedule(event_handler, path, recursive=True)
    observer.start()
    print("server is ready.")
    # 下面的代码避免出错中断(双击.py文件启动时)
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

版权声明:本文为qq_38622141原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。