How do I watch a file for changes?

前端 未结 25 2781
孤街浪徒
孤街浪徒 2020-11-21 07:13

I have a log file being written by another process which I want to watch for changes. Each time a change occurs I\'d like to read the new data in to do some processing on it

25条回答
  •  孤独总比滥情好
    2020-11-21 07:51

    related @4Oh4 solution a smooth change for a list of files to watch;

    import os
    import sys
    import time
    
    class Watcher(object):
        running = True
        refresh_delay_secs = 1
    
        # Constructor
        def __init__(self, watch_files, call_func_on_change=None, *args, **kwargs):
            self._cached_stamp = 0
            self._cached_stamp_files = {}
            self.filenames = watch_files
            self.call_func_on_change = call_func_on_change
            self.args = args
            self.kwargs = kwargs
    
        # Look for changes
        def look(self):
            for file in self.filenames:
                stamp = os.stat(file).st_mtime
                if not file in self._cached_stamp_files:
                    self._cached_stamp_files[file] = 0
                if stamp != self._cached_stamp_files[file]:
                    self._cached_stamp_files[file] = stamp
                    # File has changed, so do something...
                    file_to_read = open(file, 'r')
                    value = file_to_read.read()
                    print("value from file", value)
                    file_to_read.seek(0)
                    if self.call_func_on_change is not None:
                        self.call_func_on_change(*self.args, **self.kwargs)
    
        # Keep watching in a loop
        def watch(self):
            while self.running:
                try:
                    # Look for changes
                    time.sleep(self.refresh_delay_secs)
                    self.look()
                except KeyboardInterrupt:
                    print('\nDone')
                    break
                except FileNotFoundError:
                    # Action on file not found
                    pass
                except Exception as e:
                    print(e)
                    print('Unhandled error: %s' % sys.exc_info()[0])
    
    # Call this function each time a change happens
    def custom_action(text):
        print(text)
        # pass
    
    watch_files = ['/Users/mexekanez/my_file.txt', '/Users/mexekanez/my_file1.txt']
    
    # watcher = Watcher(watch_file)  # simple
    
    
    
    if __name__ == "__main__":
        watcher = Watcher(watch_files, custom_action, text='yes, changed')  # also call custom action function
        watcher.watch()  # start the watch going
    

提交回复
热议问题