我正在尝试编写一个监视特定日志文件以进行修改的脚本,但我无法看到任何.txt文件。它适用于其他类型的文件。
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from os.path import expanduser
file_to_watch = 'test.txt'
class FileModifiedHandler(FileSystemEventHandler):
def __init__(self, path, file_name, callback):
self.file_name = file_name
self.callback = callback
self.observer = Observer()
self.observer.schedule(self, path, recursive=False)
self.observer.start()
self.observer.join()
def on_modified(self, event):
print "Event: %s" % (event)
print "Ends with %s: %s" % (self.file_name, event.src_path.endswith(self.file_name))
if not event.is_directory and event.src_path.endswith(self.file_name):
self.callback()
if __name__ == '__main__':
def callback():
print("FILE WAS MODIFIED")
FileModifiedHandler('.', file_to_watch, callback)
当我将file_to_watch设置为.py文件时,日志会返回正确的源路径,但是当我将其更改为同一文件夹中的.txt文件时,它会在目录中停止。我不确定这是什么原因。这是程序返回的内容:
Event: <FileModifiedEvent: src_path='/Users/nick/Documents/Python/WatchdogTest.py'>
Ends with WatchdogTest.py: True
FILE WAS MODIFIED
Event: <DirModifiedEvent: src_path='/Users/nick/Documents/Python'>
Ends with test.txt: False
答案 0 :(得分:0)
你可以将文件test.txt
重命名为其他名称吗mytest.txt
我觉得/ t被区别对待,或者你可以添加转义序列来绕过。