我有一个 perl 脚本,可以将文件从一个传入目录分类到 Ubuntu 服务器上的其他目录中。 现在,我每隔几分钟将它作为 cron 作业运行一次,但如果在将文件写入传入目录时启动脚本,它可能会出现问题。
更好的解决方案是在将文件写入传入目录或任何子目录时启动它。
我在想我可以运行另一个脚本作为服务,只要发生目录更改,它就会调用我的排序脚本,但是我不知道如何去做。
请您参考如下方法:
在 Linux 上,您可以使用 pyinotify 库:https://github.com/seb-m/pyinotify
要查看子目录,请在 add_watch() 调用中使用 rec=True。完整示例监控/tmp 目录及其子目录以创建文件:
import pyinotify
class EventHandler(pyinotify.ProcessEvent):
def process_IN_CREATE(self, event):
# Processing of created file goes here.
print "Created:", event.pathname
wm = pyinotify.WatchManager()
notifier = pyinotify.Notifier(wm, EventHandler())
wm.add_watch('/tmp', pyinotify.IN_CREATE, rec=True)
notifier.loop()
