我正在使用 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/