python - Python看门狗子进程队列
问题描述
我从以下网站复制了一个 Python 看门狗脚本:https ://www.michaelcho.me/article/using-pythons-watchdog-to-monitor-changes-to-a-directory
import time
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
class Watcher:
DIRECTORY_TO_WATCH = "/path/to/my/directory"
def __init__(self):
self.observer = Observer()
def run(self):
event_handler = Handler()
self.observer.schedule(event_handler, self.DIRECTORY_TO_WATCH, recursive=True)
self.observer.start()
try:
while True:
time.sleep(5)
except:
self.observer.stop()
print "Error"
self.observer.join()
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
# Take any action here when a file is first created.
print "Received created event - %s." % event.src_path
# Build up queue of subtasks here and let another thread/process
# take care of it so that main process can continue.
elif event.event_type == 'modified':
# Taken any action here when a file is modified.
print "Received modified event - %s." % event.src_path
if __name__ == '__main__':
w = Watcher()
w.run()
这个脚本很适合我,但我还有一些额外的要求。
我不想打印文本,而是想启动一个可能需要几分钟的额外进程(Python 脚本)。主脚本不应等待此过程完成,而是继续检查新文件或更改的文件。
被启动的二级进程是不允许互相超车的,所以必须放在某种需要串行处理的队列中。
什么方法/包是解决这些要求的好方法?我简要地查看了多处理和异步,但不确定正确的实现。
我的一般想法是应该在事件类型上启动一个单独的进程/线程,检查队列并一个一个地通过。理想情况下,当主进程关闭时,这个辅助线程/进程会完成剩余的队列。
解决方案
我将此模板用于看门狗。on_any_event
在我的情况下有点敏感。
回答 1.:你可以用任何东西代替print
. 当事件发生时,函数、方法、循环等 Watcher
将继续运行和调用。Handler()
认为您需要详细说明在on_any_event
调用之后您想要做什么。
class Handler(FileSystemEventHandler):
@staticmethod
def on_any_event(event):
if event.is_directory:
return None
elif event.event_type == 'created':
return run_function()
elif event.event_type == 'modified':
return run_other_function()
def run_function():
W = '36 Chambers\n'
with open('Wu-Tang.txt', '') as wu:
wu.write(W)
wu.close()
def run_other_function():
_W = 'The RZA the GZA.\n'
with open('Wu-Tang.txt', 'a') as _wu:
_wu.write(_W)
_wu.close()
if __name__ == '__main__':
w = Watcher()
w.run()
推荐阅读
- apache - Traefik 在后端重定向的情况下不会修改位置标头
- digital-ocean - 如何获取运行 Kubernetes cert-manager 的证书
- vba - 如何将信息输出到列表框?
- javascript - 将 Lottie SVG 居中到 Header 元素
- pycharm - 最新的 Pycharm 对 brew 安装版本说“Interpeter 似乎无效”
- android - 哪个是好的WebRtc或wifi P2P可以将音频从一台设备共享到另一台设备
- webpack - 是否可以创建独立的块以在不同的应用程序中重复使用?
- docker - docker-compose vs 创建和运行图像
- react-native - 如何修复反应原生博览会起始代码?
- google-cloud-platform - 是否可以使用 Google Scheduler API 安排作业?