【问题标题】:Getting the filename using python Watchdog使用 python Watchdog 获取文件名
【发布时间】:2016-07-12 23:26:21
【问题描述】:

我正在尝试获取定期更改的文件的名称。 我正在使用看门狗来做到这一点。

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

timestr = time.strftime("%Y.%m.%d-%H.%M.%S")

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        change_log = open('change_log_' + timestr + '.txt', 'aw')
        change_log.write('Time the file changed: ' + timestr + '\n')
        change_log.close()

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path='.', recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

由于某种原因,这会在“change_log”文件中打印出大约 62 行。这不是很有用。 我想做的是打印更改的文件的名称,或将其存储在变量中以传递给我的其他模块。

【问题讨论】:

    标签: python variables filesystems output watchdog


    【解决方案1】:

    在您的示例中,如果您需要文件名,则需要将'change_log_' 替换为event.src_path。有关详细信息,请参阅official code。 您还可以看到event.src_paththis answer 中的使用,就像我在打印输出中使用的一样。

    【讨论】:

      【解决方案2】:

      看起来发送到您的处理程序的事件对象包含您寻找的信息: http://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEvent

      使用传递到FileSystemEvent 子类处理程序方法的事件对象的src_path 属性来获取文件名。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-27
        • 1970-01-01
        • 2012-07-31
        • 2014-06-24
        • 2015-10-26
        相关资源
        最近更新 更多