看门狗监视文件中的更改 [英] watchdog monitoring file for changes
本文介绍了看门狗监视文件中的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要查看日志文件中的更改.看完stackoverflow问题后,我看到有人推荐 watchdog
.因此,我正在尝试进行测试,并且不确定文件更改时在哪里添加代码:
I have a need to watch a log file for changes. After looking through stackoverflow questions, I see people recommending watchdog
. So I'm trying to test, and am not sure where to add the code for when files change:
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
循环中,是否已添加/更改文件?
Where do I add the "got it" — in the while
loop if the files have been added/changed?
推荐答案
而不是 LoggingEventHandler
定义您的处理程序:
Instead of LoggingEventHandler
define your handler:
#!/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
.
on_modified
is called when a file or directory is modified.
这篇关于看门狗监视文件中的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文