我正在尝试在pyqt5中构建文件侦听器应用程序。我的代码可以按我的意愿工作,但我想对其进行改进。
有一个简单的按钮Listen
。当我单击它时,它会打开一个记事本,并开始一直监听直到a.txt
文件存在。存在后,存在新按钮Start
,旧按钮被删除。
我的问题是;我的GUI在监听a.txt
文件甚至我使用threading
时冻结。我使用错了吗?您可以修复我的代码吗?
我的主要代码;
from PyQt5 import QtCore, QtWidgets
import sys
import os
class ListenWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ListenWindow, self).__init__(parent)
self.setWindowTitle("Listen")
self.button_listen = QtWidgets.QPushButton('Listen', self)
font1 = self.button_listen.font()
font1.setPointSize(10)
self.button_listen.setFont(font1)
self.button_listen.setFixedSize(200, 50)
self.button_listen.clicked.connect(self.startToListen)
self.v_box1 = QtWidgets.QVBoxLayout(self)
self.v_box1.addWidget(self.button_listen)
self.h_box1 = QtWidgets.QHBoxLayout(self)
self.v_box1.addLayout(self.h_box1)
def abc(self):
while not os.path.exists('C:/Users/Wicaledon/PycharmProjects/myproject/a.txt'):
pass
if os.path.isfile('C:/Users/Wicaledon/PycharmProjects/myproject/a.txt'):
self.button_start = QtWidgets.QPushButton('Start', self)
font2 = self.button_start.font()
font2.setPointSize(10)
self.button_start.setFont(font2)
self.button_start.setFixedSize(200, 50)
self.h_box1.addWidget(self.button_start, 0, QtCore.Qt.AlignCenter)
else:
raise ValueError("%s isn't a file!" % 'C:/Users/Wicaledon/PycharmProjects/myproject/a.txt')
self.v_box1.removeWidget(self.button_listen)
def startToListen(self):
def thread_function(my_text):
import subprocess
import os
FNULL = open(os.devnull, 'w')
args = my_text
subprocess.call(args, stdout=FNULL, stderr=FNULL, shell=True)
# os.system(my_text)
return
import threading
my_text = "notepad"
x = threading.Thread(target=thread_function,args=(my_text,))
x.start()
y = threading.Thread(target=ListenWindow.abc(self))
y.start()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = ListenWindow()
window.setWindowTitle('Login')
window.show()
sys.exit(app.exec_())
我的用于创建a.txt
的代码;
f=open("a.txt", "w+")
f.write("delete_me")
f.close()
使用这种简单的while方法检查文件是否存在不是一件好事,因为它不必要地消耗了很多CPU资源。同样,在处理UI时,使用任何类型的循环(while / for或递归函数调用)也是一个坏主意:如您所见,它阻塞了接口;尽管abhilb提出的solution似乎可行,但它只是使UI响应,但无论如何关闭程序且尚未创建文件,无论如何都会使CPU保持峰值。
[PyQt已经具有文件侦听器QFileSystemWatcher,并且应避免使用Qt外部系统已经提供的文件侦听器,这不仅对文件监视程序而且对线程都很重要。
另一个要记住的重要方面是Qt有其自己的事件循环,并且使用python的线程与其进行交互不是一个好主意(事实上,every UI交互必须在主线程,即使使用Qt的线程也是如此。
如果您真的想做一个基本的文件侦听器(例如,出于学习目的),您至少应该在一个周期内添加一个服务员,并且该周期必须在另一个线程中,否则GUI将会是仍然被阻止。
以下是完全基于Qt的实现,基于您的代码。
import sys
from PyQt5 import QtCore, QtWidgets
fileToWatch = 'C:/Users/Wicaledon/PycharmProjects/myproject/a.txt'
editorProgram = 'notepad'
class ListenWindow(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ListenWindow, self).__init__(parent)
self.setWindowTitle("Listen")
self.button_listen = QtWidgets.QPushButton('Listen', self)
font1 = self.button_listen.font()
font1.setPointSize(10)
self.button_listen.setFont(font1)
self.button_listen.setFixedSize(200, 50)
self.button_listen.clicked.connect(self.startToListen)
self.v_box1 = QtWidgets.QVBoxLayout(self)
self.v_box1.addWidget(self.button_listen)
# no parent with an already existing layout should be set for a new
# layout; in this case, the current widget already has the v_box1 layout
# set, therefore the new h_box1 layout should have no argument
self.h_box1 = QtWidgets.QHBoxLayout()
self.v_box1.addLayout(self.h_box1)
self.listener = QtCore.QFileSystemWatcher(self)
self.listener.directoryChanged.connect(self.checkFile)
def startToListen(self):
fileInfo = QtCore.QFileInfo(fileToWatch)
if fileInfo.exists():
self.createStart()
return
elif fileInfo.absolutePath() not in self.listener.directories():
self.listener.addPath(fileInfo.absolutePath())
# create an empty file so that there's no error when trying to open
# it in the editor
emptyFile = QtCore.QFile(fileToWatch)
emptyFile.open(emptyFile.WriteOnly)
emptyFile.close()
process = QtCore.QProcess(self)
process.start(editorProgram, [fileToWatch])
# optional: disable the interface until the program has quit
self.setEnabled(False)
process.finished.connect(lambda: self.setEnabled(True))
def checkFile(self, path):
fileInfo = QtCore.QFileInfo(fileToWatch)
if fileInfo.exists():
if self.h_box1:
# the layout already contains the start button, ignore
return
else:
self.createStart()
else:
# file has been [re]moved/renamed, maybe do something here...
pass
def createStart(self):
self.button_start = QtWidgets.QPushButton('Start', self)
font2 = self.button_start.font()
font2.setPointSize(10)
self.button_start.setFont(font2)
self.button_start.setFixedSize(200, 50)
self.h_box1.addWidget(self.button_start, 0, QtCore.Qt.AlignCenter)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
window = ListenWindow()
window.setWindowTitle('Login')
window.show()
sys.exit(app.exec_())
将while
功能中的abc
循环更改为
while not os.path.exists('b.txt'):
QtCore.QCoreApplication.processEvents()
pass