won*_*der 2 python-2.7 python-multiprocessing
我有一组由应用程序创建的 100 个文件。文件不是按顺序动态更新的。使用 Python,我正在尝试读取文件。但是,我不知道哪个文件在什么时间更新。
我不想每次都遍历每个文件来检查实例中更新了哪些文件。我可以创建多个进程/线程来触发文件更新的主进程。有没有其他方式像文件更新可以通知主python进程,以便只读取那些文件??
谢谢。
小智 5
试试 python 模块“看门狗”。它将启动一个文件或文件夹观察器,可用于启动文件/文件夹更改功能。 https://pypi.python.org/pypi/watchdog
下面的示例将监视一个文件夹并通知其中文件的每次更改。如果您只想要特定事件,请参阅文档。 https://pythonhosted.org/watchdog/api.html#watchdog.events.FileSystemEventHandler
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class EventHandler(FileSystemEventHandler):
def on_any_event(self, event):
print event
if __name__ == "__main__":
path = "/PATH/TO/YOUR/FOLDER"
event_handler = EventHandler()
observer = Observer()
observer.schedule(event_handler, path, recursive=True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
Run Code Online (Sandbox Code Playgroud)