问题描述
我正在尝试编写一个脚本来监视特定的日志文件以进行修改,但我无法让它看到任何 .txt 文件.它适用于其他类型的文件.
I'm trying to write a script that watches a specific log file for modification, but I can't get it to see any .txt files. It works fine with other types of files.
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 文件时,它会停在该目录中.我不确定这是什么原因.这是程序返回的内容:
When I set file_to_watch to a .py file, the log returns the correct source path, but when I change it to a .txt file in the same folder, it stops at the directory. I'm not sure what the reason for this is. Here is what the program returns:
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
推荐答案
can you rename file test.txt
to some other name say mytest.txt
我觉得/t 被区别对待,或者您可以添加转义序列以绕过.
can you rename file test.txt
to some other name say mytest.txt
I feel like /t is treated differently or may be you can add escape sequence to bypass.
这篇关于Python Watchdog - src_path 不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!