How do I watch a file for changes?

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

    If you want a multiplatform solution, then check QFileSystemWatcher. Here an example code (not sanitized):

    from PyQt4 import QtCore
    
    @QtCore.pyqtSlot(str)
    def directory_changed(path):
        print('Directory Changed!!!')
    
    @QtCore.pyqtSlot(str)
    def file_changed(path):
        print('File Changed!!!')
    
    fs_watcher = QtCore.QFileSystemWatcher(['/path/to/files_1', '/path/to/files_2', '/path/to/files_3'])
    
    fs_watcher.connect(fs_watcher, QtCore.SIGNAL('directoryChanged(QString)'), directory_changed)
    fs_watcher.connect(fs_watcher, QtCore.SIGNAL('fileChanged(QString)'), file_changed)
    

提交回复
热议问题