我需要帮助才能在修改文件时调用my_custom_function。我还想拥有file_change,file_delete等文件的状态。我使用了看门狗,它支持预定义函数作为schedule()的第一个参数。我应该可以进行自定义调用并对其进行一些操作。我的用例是使用watchdog在文件修改之前和文件修改之后获取文件内容。
import sys
import time
import logging
from watchdog.observers import Observer
import os
def my_custom_function():
print "---"
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
path = os.path.abspath(".")
my_event = my_custom_function()
observer = Observer()
observer.schedule(my_event, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
答案 0 :(得分:1)
希望以下代码能够回答您的问题。
import sys
import time
import watchdog
from watchdog.observers import Observer
from watchdog.events import PatternMatchingEventHandler
import time
from threading import Thread
class MyHandler(PatternMatchingEventHandler):
def process(self, event):
print "I am being processed"
def on_modified(self, event):
print "file modified " + event.src_path
self.process(event)
def on_created(self, event):
print "file created" + event.src_path
self.process(event)
def on_moved(self, event):
print "file moved" + event.src_path
self.process(event)
def on_deleted(self, event):
print "file deleted" + event.src_path
self.process(event)
if __name__ == '__main__':
args = sys.argv[1:]
observer = Observer()
observer.schedule(MyHandler(), path=args[0] if args else '.')
print "Start"
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()