OS X 上的 Python 中的看门狗库——不显示完整的事件路径

2024-01-06

我刚刚开始与看门狗库 http://pythonhosted.org/watchdog/在 Mac 上的 Python 中,我正在做一些基本测试,以确保一切按照我的预期工作。不幸的是,它们不是——我似乎只能获取包含注册事件的文件的文件夹的路径,而不是文件本身的路径。

下面是一个简单的测试程序(对 Watchdog 提供的示例稍作修改),用于在注册事件时打印出事件类型、路径和时间。

import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
from watchdog.events import FileSystemEventHandler

class TestEventHandler(FileSystemEventHandler):

def on_any_event(self, event):
    print("event noticed: " + event.event_type + 
                 " on file " + event.src_path + " at " + time.asctime())

if __name__ == "__main__":
    event_handler = TestEventHandler()
    observer = Observer()
    observer.schedule(event_handler, path='~/test', recursive=True)
    observer.start()
    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

src_path 变量应包含发生事件的文件的路径。

但是,在我的测试中,当我修改文件时, src_path 仅打印包含该文件的文件夹的路径,而不是文件本身的路径。例如,当我修改文件时moon.txt在文件夹中europa,程序打印以下输出:

event noticed: modified on file ~/test/europa at Mon Jul  8 15:32:07 2013

为了获取修改文件的完整路径,我需要更改什么?


问题解决了。事实证明,FSEvents在 OS X 中,仅返回文件修改事件的目录,让您自己扫描目录以找出哪个文件被修改。 Watchdog 文档中没有提到这一点,但很容易在FSEvents文档。

为了获取文件的完整路径,我添加了以下代码片段(受到 StackOverflow 线程的启发 https://stackoverflow.com/questions/2014554/find-the-newest-folder-in-a-directory-in-python) 查找目录中最近修改的文件,每当 event.src_path 返回目录时就使用该文件。

if(event.is_directory):
    files_in_dir = [event.src_path+"/"+f for f in os.listdir(event.src_path)]
    mod_file_path = max(files_in_dir, key=os.path.getmtime)

mod_file_path包含已修改文件的完整路径。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

OS X 上的 Python 中的看门狗库——不显示完整的事件路径 的相关文章

随机推荐