How do I watch a file for changes?

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

    I'd try something like this.

        try:
                f = open(filePath)
        except IOError:
                print "No such file: %s" % filePath
                raw_input("Press Enter to close window")
        try:
                lines = f.readlines()
                while True:
                        line = f.readline()
                        try:
                                if not line:
                                        time.sleep(1)
                                else:
                                        functionThatAnalisesTheLine(line)
                        except Exception, e:
                                # handle the exception somehow (for example, log the trace) and raise the same exception again
                                raw_input("Press Enter to close window")
                                raise e
        finally:
                f.close()
    

    The loop checks if there is a new line(s) since last time file was read - if there is, it's read and passed to the functionThatAnalisesTheLine function. If not, script waits 1 second and retries the process.

提交回复
热议问题