2

Mac で Python のWatchdog ライブラリを使い始めたばかりで、期待どおりに動作することを確認するためにいくつかの基本的なテストを行っています。残念ながら、そうではありません。ファイル自体へのパスではなく、イベントが登録されたファイルを含むフォルダーへのパスしか取得できないようです。

以下は、イベントが登録されるたびにイベントの種類、パス、および時刻を出力する簡単なテスト プログラム (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

変更されたファイルへのフル パスを取得するには、何を変更する必要がありますか?

4

2 に答える 2

1

Thanks ekl for providing your solution. I just stumbled across the same problem. However, I used to use PatternMatchingEventHandler, which requires small changes to your solution:

  • subclass from FileSystemEventHandler
  • create an attribute pattern where you store your pattern matching. This is not as flexible as the original PatternMatchingEventHandler, but should suffice most needs, and you will get the idea anyway if you want to extend it.

Here's the code you have to put in your FileSystemEventHandlersubclass:

def __init__(self, pattern='*'):
    super(MidiEventHandler, self).__init__()
    self.pattern = pattern


def on_modified(self, event):
    super(MidiEventHandler, self).on_modified(event)

    if event.is_directory:
        files_in_dir = [event.src_path+"/"+f for f in os.listdir(event.src_path)]
        if len(files_in_dir) > 0:
            modifiedFilename = max(files_in_dir, key=os.path.getmtime)
        else:
            return
    else:
        modifiedFilename = event.src_path

    if fnmatch.fnmatch(os.path.basename(modifiedFilename), self.pattern):
        print "Modified MIDI file: %s" % modifiedFilename

One other thing I changed is that I check whether the directory is empty or not before running max() on the file list. max() does not work with empty lists.

于 2013-09-14T01:26:05.167 に答える