I am working on a home automation project with a Raspberry Pi 3 and I need to run some python scripts when a txt file changes. Is there a way to watch if the file is changed? (Currently i use a python script which constantly opens the txt and checks if anything changed but its not efficient and it causes problems sometimes. Thanks in advance!
-
2Watchdog should tell you when there are file changesinspectorG4dget– inspectorG4dget2017-06-22 16:23:03 +00:00Commented Jun 22, 2017 at 16:23
-
Is the txt file changing predictible?Miguel Ortiz– Miguel Ortiz2017-06-22 16:46:28 +00:00Commented Jun 22, 2017 at 16:46
-
No, the client changes the value when he wants.Chris– Chris2017-06-24 11:52:29 +00:00Commented Jun 24, 2017 at 11:52
Add a comment
|
1 Answer
If you wanted to report changes to a single file in the local directory called foo.txt you can use watchdog (which is a skin over inotify, or equivalent) like this:
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()