每当在目录中创建文件时,如何运行 python 脚本?

Fol*_*ann 8 python scripts automation directory inotify

所以,我正在尝试做这个有点简单的任务,但我还没有成功。我希望现在有所改变。

目标:

运行/var/www/lager-scanner/filer/pluk_script.py每当有一个新的文件/var/www/lager-scanner/filer/Nav/FromNav,并运行此作为www-data用户。

有没有人可以告诉我怎么做?

中的所有文件夹/var/www均归www-data用户和组所有并具有775权限。

Jac*_*ijm 8

不是骗子,而是在这个问题的公认答案中,解释了在任意目录中添加或创建文件时如何运行脚本(或任何命令)。在您的情况下,唯一需要的事件触发器是:

-e create
Run Code Online (Sandbox Code Playgroud)

此外,由于您没有使用文件路径作为参数,您可以跳过--format-section。

在后台运行的脚本就是:

#!/bin/bash
DIR="/var/www/lager-scanner/filer/Nav/FromNav"
inotifywait -m -r -e create "$DIR" | while read f

do
    # you may want to release the monkey after the test :)
    echo monkey
    # <whatever_command_or_script_you_liketorun>
done
Run Code Online (Sandbox Code Playgroud)

解释

如链接问题中所述:

-e create
Run Code Online (Sandbox Code Playgroud)

会注意到在目录中创建的新文件。

选项:

-m -r 
Run Code Online (Sandbox Code Playgroud)

是使命令无限期地运行(“监视”)并在目录中递归运行。

根据,使用pyinotify是不是最好的选择。

编辑

在评论你提到它不工作,你提到的目标文件夹是远程的。虽然不完全相同,但问题似乎与有关:
内核看不到更改;它完全是远程发生的。

一个(经过测试的)解决方法是在本地安装远程文件夹。