How do I watch a file for changes?

前端 未结 25 2770
孤街浪徒
孤街浪徒 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 08:10

    This is another modification of Tim Goldan's script that runs on unix types and adds a simple watcher for file modification by using a dict (file=>time).

    usage: whateverName.py path_to_dir_to_watch

    #!/usr/bin/env python
    
    import os, sys, time
    
    def files_to_timestamp(path):
        files = [os.path.join(path, f) for f in os.listdir(path)]
        return dict ([(f, os.path.getmtime(f)) for f in files])
    
    if __name__ == "__main__":
    
        path_to_watch = sys.argv[1]
        print('Watching {}..'.format(path_to_watch))
    
        before = files_to_timestamp(path_to_watch)
    
        while 1:
            time.sleep (2)
            after = files_to_timestamp(path_to_watch)
    
            added = [f for f in after.keys() if not f in before.keys()]
            removed = [f for f in before.keys() if not f in after.keys()]
            modified = []
    
            for f in before.keys():
                if not f in removed:
                    if os.path.getmtime(f) != before.get(f):
                        modified.append(f)
    
            if added: print('Added: {}'.format(', '.join(added)))
            if removed: print('Removed: {}'.format(', '.join(removed)))
            if modified: print('Modified: {}'.format(', '.join(modified)))
    
            before = after
    

提交回复
热议问题