python - 当txt文件更改时运行python脚本

标签 python raspberry-pi

我正在使用 Raspberry Pi 3 开发一个家庭自动化项目,当 txt 文件发生更改时,我需要运行一些 python 脚本。有没有办法查看文件是否被更改? (目前我使用一个 python 脚本,它不断打开 txt 并检查是否有任何更改,但效率不高,有时会导致问题。 提前致谢!

最佳答案

如果您想报告对本地目录中名为 foo.txt 的单个文件的更改,您可以使用 watchdog (这是 inotify 的皮肤,或等效的),如下所示:

from time import sleep
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class Handler(FileSystemEventHandler):
    def on_modified(self, event):
        if event.src_path == "./foo.txt": # in this example, we only care about this one file
            print ("changed")

observer = Observer()
observer.schedule(Handler(), ".") # watch the local directory
observer.start()

try:
    while True:
        sleep(1)
except KeyboardInterrupt:
    observer.stop()

observer.join()

关于python - 当txt文件更改时运行python脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44704732/

相关文章:

python - 使用带 raspi 相机的 flask 进行视频流传输

python - pip 无法确认 SSL 证书 : SSL module is not available

java - 为什么 Apache POI 能够编写超过 255 个字符的超链接,而 XLSXWriter 却不能?

python - 使用 while 循环查找输入数字的平均值并使用 break 语句退出循环的程序

linux - 如何使用 bash/terminal 将命令传递给自定义 Linux 服务

javascript - 验证 Raspberry Pi http 请求

python - 如何在 Raspbian Buster 上使用 headless Firefox 设置 Selenium

Azure 应用服务上的 Python 代码运行速度比本地慢 10 倍

python - 我可以让 uuid 更随机吗?

python - 下载适用于 Python 的 SQL 时出错