How do I watch a file for changes?

前端 未结 25 2839
孤街浪徒
孤街浪徒 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条回答
  •  Happy的楠姐
    2020-11-21 08:03

    Here's an example geared toward watching input files that write no more than one line per second but usually a lot less. The goal is to append the last line (most recent write) to the specified output file. I've copied this from one of my projects and just deleted all the irrelevant lines. You'll have to fill in or change the missing symbols.

    from PyQt5.QtCore import QFileSystemWatcher, QSettings, QThread
    from ui_main_window import Ui_MainWindow   # Qt Creator gen'd 
    
    class MainWindow(QMainWindow, Ui_MainWindow):
        def __init__(self, parent=None):
            QMainWindow.__init__(self, parent)
            Ui_MainWindow.__init__(self)
            self._fileWatcher = QFileSystemWatcher()
            self._fileWatcher.fileChanged.connect(self.fileChanged)
    
        def fileChanged(self, filepath):
            QThread.msleep(300)    # Reqd on some machines, give chance for write to complete
            # ^^ About to test this, may need more sophisticated solution
            with open(filepath) as file:
                lastLine = list(file)[-1]
            destPath = self._filemap[filepath]['dest file']
            with open(destPath, 'a') as out_file:               # a= append
                out_file.writelines([lastLine])
    

    Of course, the encompassing QMainWindow class is not strictly required, ie. you can use QFileSystemWatcher alone.

提交回复
热议问题