python - watchdog.observers.Observer 在 Windows 中工作,在 Linux 上的 docker 中工作,在 Windows 上的 docker 中不起作用
问题描述
我有一个有趣的问题让我发疯。我有一个使用 watchdog.observers.Observer 的 python 程序。这个程序(又名观察者)监视一个文件夹并在文件出现在其中时做出响应。我有另一个程序(又名解析器),它定期用文件填充监视的文件夹。
- 当观察程序运行在 Windows 中,解析器运行在 Windows 上的 docker 容器中时,就会有幸福感。
- 当观察程序在 Linux 机器上的 docker 容器中运行,而解析器在 Linux 机器上的另一个 docker 容器中运行时,就会有幸福感。
- 当 watcher 程序在 Windows 上的一个 docker 容器中运行而解析器在 Windows 上的另一个 docker 容器中运行时,幸福感并没有实现。解析器用文件填充文件夹,但观察者从不观察它们。
这是我的观察者代码:
import os
import sys
import time
from watchdog.observers import Observer
from event_handler import ImagesEventHandler
from constants import ROOT_FOLDER, IMAGES_FOLDER, CWD
class ImagesWatcher:
def __init__(self, src_path):
self.__src_path = src_path
print(self.__src_path)
self.__event_handler = ImagesEventHandler()
self.__event_observer = Observer()
print("********** Inside ImagesWatcher --init__ method just after instantiating ImagesEventHandler and Observer **************")
def run(self):
print("********** Inside ImagesWatcher run method **************")
self.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
self.stop()
def start(self):
print("********** Inside ImagesWatcher start method **************")
self.__schedule()
self.__event_observer.start()
def stop(self):
print("********** Inside ImagesWatcher stop method **************")
self.__event_observer.stop()
self.__event_observer.join()
def __schedule(self):
print("********** Inside ImagesWatcher __schedule method **************")
print(self.__src_path)
self.__event_observer.schedule(
self.__event_handler,
self.__src_path,
recursive=True
)
if __name__ == "__main__":
src_path = sys.argv[1] if len(sys.argv) > 1 else CWD
src_path = os.path.abspath(src_path)
watch_path = os.path.join(src_path, ROOT_FOLDER)
watch_path = os.path.join(watch_path, IMAGES_FOLDER)
print('watch_path: ' + watch_path)
if not os.path.exists(watch_path):
os.makedirs(watch_path)
print('just created: ' + watch_path)
ImagesWatcher(watch_path).run()
这是相关的事件处理程序代码:
import os
from PIL import Image
from watchdog.events import FileSystemEventHandler
from lambda_function import lambda_handler
from time import sleep
from os.path import dirname, abspath
class ImagesEventHandler(FileSystemEventHandler):
def __init__(self,):
print("********** Inside event handler __init__ method **************")
def on_created(self, event):
print("********** Inside event handler on_created method **************")
self.process(event)
def process(self, event):
print("********** Inside event handler process method **************")
sleep(2)
image = Image.open(event.src_path)
tracking_dir=os.path.join(dirname(dirname(abspath(event.src_path))),'Tracking')
print("******************** tracking_dir: ' + tracking_dir + ' ********************")
lambda_handler(image,tracking_dir)
观察者的停止方法永远不会执行。事件处理程序的 init 方法被执行,但是 on_created 和 process 方法都没有被执行。
以下是我构建和运行 docker 容器的方法:
docker build -t watcher -f docker/watcher/Dockerfile .
docker run -d --network onprem_network -v c:\My_MR:/code/My_MR --name watcher watcher
docker build -t parser -f docker/parser/Dockerfile .
docker run -d --network onprem_network -v c:\My_MR:/code/My_MR --name parser parser
我的观察者 Dockerfile:
FROM python:3.7.9
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
COPY requirements.txt /requirements.txt
RUN pip install --upgrade pip -r /requirements.txt && mkdir /code
WORKDIR /code
COPY . /code/
RUN apt update && apt-get update && apt install tesseract-ocr -y && apt-get install ffmpeg libsm6 libxext6 -y
CMD ["python", "/code/watcher.py"]
我的解析器 Dockerfile:
FROM python:3.7.9
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
COPY requirements.txt /requirements.txt
RUN pip install --upgrade pip -r /requirements.txt && mkdir /code
WORKDIR /code
COPY . /code/
RUN apt update && apt-get update && apt-get install ffmpeg -y
CMD ["python", "/code/parser.py"]
我的要求.txt:
Pillow == 5.4.1
gql == 3.0.0a5
matplotlib == 3.0.3
numpy == 1.16.2
opencv_python == 4.4.0.44
pandas == 0.24.2
pytesseract == 0.2.6
python_ffmpeg_video_streaming == 0.1.14
watchdog == 2.0.2
requests
tesseract
任何帮助将不胜感激。
解决方案
Docker Windows 卷观察器
也可以使用Docker Windows Volume Watcher。Python 脚本监视托管在 Windows 上的 Docker 容器的文件夹绑定,并使用文件更改更新这些容器。
使用安装pip
(支持 Python 2 和 3)。
pip install docker-windows-volume-watcher
监控所有容器的所有目录绑定。
docker-volume-watcher
仅监视容器 container_name 的绑定。
docker-volume-watcher container_name
仅监视 container_name 与主机目录 C:\some\directory 的绑定。
docker-volume-watcher container_name C:\some\directory
限制
- 该脚本不会传播到容器文件删除事件。
- 该脚本需要在容器中安装 stat 和 chmod utils。
https://forums.docker.com/t/file-system-watch-does-not-work-with-mounted-volumes/12038/9 http://blog.subjectify.us/miscellaneous/2017/04/24 /docker-for-windows-watch-bindings.html
看门狗和 PollingObserver()
另一种解决方案是使用类PollingObserver
。但是,如果看门狗必须使用一个时间表监控多个文件和文件夹,则速度会明显变慢。
import sys
import time
import logging
from watchdog.observers.polling import PollingObserver
from watchdog.events import LoggingEventHandler
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
event_handler = LoggingEventHandler()
observer = PollingObserver()
# Limit the number of files by setup multiple schedule
observer.schedule(event_handler, '/folder/subfolder') # All files in a subfolder
observer.schedule(event_handler, '/folder/file') # A file
observer.schedule(event_handler, '/folder/file2') # A file
# etc...
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
推荐阅读
- python-3.x - For循环在某个范围内相乘
- c - scanf 总是打印输入的数字
- c++ - bin_search 在 C++ 中返回一个包含 15 个元素的数组
- java - 使用 LibGDX IOS 在 Android Studio 中编译时出错
- css - 如何在wordpress的类别标题中隐藏鼠标悬停代码?
- javascript - 检查json键是否是复杂对象javascript
- angular - 错误类型错误:无法读取未定义的属性“getUsers”
- sql - 如何在存储过程中声明一行不存在?
- c++ - 尝试增加数组大小时无法读取内存
- android - Android LiveData
- > 投射到 LiveData
- >