伙计们,我需要查看日志文件以进行更改。在查看了stackoverflow问题之后,我看到人们推荐“看门狗”。所以我正在尝试测试,并且不确定在文件更改时添加代码的位置:
#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
event_handler = LoggingEventHandler()
observer = Observer()
observer.schedule(event_handler, path='.', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
else:
print "got it"
except KeyboardInterrupt:
observer.stop()
observer.join()
如果文件已被添加/更改,我在哪里添加“得到它”,在while循环中?
答案 0 :(得分:81)
而不是LoggingEventHandler
定义你的处理程序:
#!/usr/bin/python
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class MyHandler(FileSystemEventHandler):
def on_modified(self, event):
print(f'event type: {event.event_type} path : {event.src_path}')
if __name__ == "__main__":
event_handler = MyHandler()
observer = Observer()
observer.schedule(event_handler, path='/data/', recursive=False)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
修改文件或目录时调用 on_modified
。
答案 1 :(得分:1)
这是一个代码段,以防止它运行两次,就像其他人在@alecxe答案中评论的一样:
from datetime import datetime, timedelta
class MyHandler(FileSystemEventHandler):
def __init__(self):
self.last_modified = datetime.now()
def on_modified(self, event):
if datetime.now() - self.last_modified < timedelta(seconds=1):
return
else:
self.last_modified = datetime.now()
print(f'Event type: {event.event_type} path : {event.src_path}')
print(event.is_directory) # This attribute is also available
答案 2 :(得分:0)
您可以使用 src_path 检查逻辑代替日期时间,因为如果检查后的逻辑超过 1 秒日期时间逻辑将失败。
class EventHandler(FileSystemEventHandler):
def __init__(self):
self.src_path = ''
def on_modified(self, event):
if self.src_path == event.src_path:
return
else:
self.src_path = event.src_path
logger.info(f"{event.event_type} occured on file {self.src_path}")
#your long processing logics goes here.