How do I watch a file, not a directory for changes using Python? -


the question: how watch file changes using python? suggests using watchdog, found able watch directory, not file. watchdog-test.py watchdog's sample script:

$ python watchdog-test.py ab_test_res.sh & [1] 30628 fbt@fbt64:~/laike9m$ traceback (most recent call last):   file "watchdog-test.py", line 15, in <module>     observer.start()   file "/usr/local/lib/python2.7/dist-packages/watchdog/observers/api.py", line 255, in start     emitter.start()   file "/usr/local/lib/python2.7/dist-packages/watchdog/utils/__init__.py", line 111, in start     self.on_thread_start()   file "/usr/local/lib/python2.7/dist-packages/watchdog/observers/inotify.py", line 121, in on_thread_start     self._inotify = inotifybuffer(path, self.watch.is_recursive)   file "/usr/local/lib/python2.7/dist-packages/watchdog/observers/inotify_buffer.py", line 35, in __init__     self._inotify = inotify(path, recursive)   file "/usr/local/lib/python2.7/dist-packages/watchdog/observers/inotify_c.py", line 187, in __init__     self._add_dir_watch(path, recursive, event_mask)   file "/usr/local/lib/python2.7/dist-packages/watchdog/observers/inotify_c.py", line 363, in _add_dir_watch     raise oserror('path not directory') oserror: path not directory 

so what's best solution? i'm using linux(ubuntu 12.04). btw don't want use polling.

you can watch file watchdog watching directory file in , responding change events effect file. you:

from watchdog.observers import observer watchdog.events import filesystemeventhandler  class filemodifiedhandler(filesystemeventhandler):      def __init__(self, path, file_name, callback):         self.file_name = file_name         self.callback = callback          # set observer watch changes in directory         self.observer = observer()         self.observer.schedule(self, path, recursive=false)         self.observer.start()         self.observer.join()      def on_modified(self, event):          # act on change we're looking         if not event.is_directory , event.src_path.endswith(self.file_name):             self.observer.stop() # stop watching             self.callback() # call callback   sys import argv, exit  if __name__ == '__main__':      if not len(argv) == 2:         print("no file specified")         exit(1)      def callback():         print("file modifed")      filemodifiedhandler('.', argv[1], callback) 

i able test on windows, should os agnostic.


Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -