How do I watch a file for changes?

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

    If polling is good enough for you, I'd just watch if the "modified time" file stat changes. To read it:

    os.stat(filename).st_mtime
    

    (Also note that the Windows native change event solution does not work in all circumstances, e.g. on network drives.)

    import os
    
    class Monkey(object):
        def __init__(self):
            self._cached_stamp = 0
            self.filename = '/path/to/file'
    
        def ook(self):
            stamp = os.stat(self.filename).st_mtime
            if stamp != self._cached_stamp:
                self._cached_stamp = stamp
                # File has changed, so do something...
    

提交回复
热议问题