python看门狗监控文件的变化
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18599339/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python watchdog monitoring file for changes
提问by Cmag
Folks, 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:
伙计们,我需要查看日志文件的更改。在查看了 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()
Where do I add the "got it", in the while loop if the files have been added/changed?
如果文件已添加/更改,我在哪里添加“得到它”,在 while 循环中?
采纳答案by alecxe
Instead of LoggingEventHandler
define your handler:
而不是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
is called when a file or directory is modified.
on_modified
在修改文件或目录时调用。
回答by run_the_race
Here's a snippet to prevent it running twice as others have commented in @alecxe answer:
这是一个片段,以防止它像其他人在@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