使用python-watchdog监视文件夹,但是当我重命名文件时,我无法找到查看新文件名的方法

时间:2014-07-06 14:46:41

标签: python python-watchdog

重命名监视程序中正在监视的文件会生成on_moved事件触发器。我遇到的问题是没有办法告诉文件被移动/重命名的内容(因为重命名文件时也会发生on_moved事件触发器)。有什么方法可以将它构建到看门狗中,还是应该在我写的程序中构建一个解决方法?

这里有一些示例代码

#!/usr/bin/python
'''
Created on 2014-07-03
'''

import sys
import time

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

'''
Extend FileSystemEventHandler to be able to write custom on_any_event method
'''
class MyHandler(FileSystemEventHandler):
    '''
    Overwrite the methods for creation, deletion, modification, and moving
    to get more information as to what is happening on output
    '''
    def on_created(self, event):
        print("created: " + event.src_path)

    def on_deleted(self, event):
        print("deleted: " + event.src_path)

    def on_modified(self, event):
        print("modified: " + event.src_path)

    def on_moved(self, event):
        print("moved/renamed: " + event.src_path)


watch_directory = sys.argv[1]       # Get watch_directory parameter

event_handler = MyHandler()

observer = Observer()
observer.schedule(event_handler, watch_directory, True)
observer.start()

'''
Keep the script running or else python closes without stopping the observer
thread and this causes an error.
'''
try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    observer.stop()
observer.join()

只要事件发生,发生了哪种类型的事件以及文件/文件夹的路径,代码就会打印出来。它需要一个参数,即要监视的文件夹的路径。

1 个答案:

答案 0 :(得分:7)

如果你不知道对象有什么方法和属性 只需在print dir(obj) event.dest_path进行此项工作