gpt4 book ai didi

python - 使用 QFileSystemWatcher 获取已更改文件的路径?

转载 作者:太空宇宙 更新时间:2023-11-03 17:18:50 26 4
gpt4 key购买 nike

摘自 How do I watch a file for changes? 中的片段:

...
@QtCore.pyqtSlot(str)
def file_changed(path):
print('File Changed!!!')
...

我假设处理程序的参数 path 是已更改的文件的路径( http://doc.qt.io/qt-4.8/qfilesystemwatcher.html 并没有真正说明应该预期的内容 表示“fileChanged ...当指定路径处的文件被修改、重命名或从磁盘中删除时,会发出信号。” )。但是,然后我运行以下示例(ubuntu 14.04,python 2.7.6,对应 py-qt4):

import sys, os
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import SIGNAL
from PyQt4 import Qt

mydir = os.path.dirname( os.path.realpath(__file__) )
myfile = os.path.join( mydir, "file.dat" )
print("myfile", myfile)

with open(myfile,"a+") as f:
f.write("line 1\n")

class MyWindow(QtGui.QWidget):
def __init__(self):
global myfile
QtGui.QWidget.__init__(self)
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
self.fs_watcher = QtCore.QFileSystemWatcher( [myfile] )
self.fs_watcher.connect(self.fs_watcher, QtCore.SIGNAL('fileChanged(const QString &)'), self.file_changed) # or just 'fileChanged(QString)'
def handleButton(self):
print ('Hello World')
@QtCore.pyqtSlot(str) #
def file_changed(path):
print('File Changed!!!' + str(path)) #

if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
window = MyWindow()
# try to trigger file change here:
with open(myfile,"a+") as f:
f.write("line 2\n")
window.show()
sys.exit(app.exec_())

...它输出:

...
File Changed!!!<__main__.MyWindow object at 0xb5432b24>
...

所以,该参数似乎没有接收更改文件的路径,而是接收对包含类的引用?!

那么如何获取已更改文件的路径?

最佳答案

如果要成为 MyWindow 的方法,file_changed 插槽需要一个 self 参数:

    @QtCore.pyqtSlot(str)
def file_changed(self, path):
print('File Changed!!!' + str(path))

关于python - 使用 QFileSystemWatcher 获取已更改文件的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33395540/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com