How do I watch a file for changes?

前端 未结 25 2763
孤街浪徒
孤街浪徒 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:52

    For watching a single file with polling, and minimal dependencies, here is a fully fleshed-out example, based on answer from Deestan (above):

    import os
    import sys 
    import time
    
    class Watcher(object):
        running = True
        refresh_delay_secs = 1
    
        # Constructor
        def __init__(self, watch_file, call_func_on_change=None, *args, **kwargs):
            self._cached_stamp = 0
            self.filename = watch_file
            self.call_func_on_change = call_func_on_change
            self.args = args
            self.kwargs = kwargs
    
        # Look for changes
        def look(self):
            stamp = os.stat(self.filename).st_mtime
            if stamp != self._cached_stamp:
                self._cached_stamp = stamp
                # File has changed, so do something...
                print('File changed')
                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: 
                    print('Unhandled error: %s' % sys.exc_info()[0])
    
    # Call this function each time a change happens
    def custom_action(text):
        print(text)
    
    watch_file = 'my_file.txt'
    
    # watcher = Watcher(watch_file)  # simple
    watcher = Watcher(watch_file, custom_action, text='yes, changed')  # also call custom action function
    watcher.watch()  # start the watch going
    

提交回复
热议问题