从PyQt线程内部启动多个线程
我现在有一个脚本,可以读取一个文件夹里的文件(有成千上万个文件),然后把这些文件放到一个列表里,再分成4个小列表。接着,我为每个小列表运行一个线程。这在Python脚本中实现起来非常简单。
thread1fileList, thread2fileList, thread3fileList, thread4fileList = load.sortFiles(fileList)
threads = [threading.Thread(target=load.threadLoad, args=(fileList, ))
for fileList in (thread1fileList, thread2fileList, thread3fileList, thread4fileList)]
for thread in threads:
thread.start()
for thread in threads:
thread.join()
不过,我现在把这段代码移到一个图形用户界面(GUI)上,使用的是Pyside。
我已经能够创建一个线程来读取文件夹里的文件(这样可以确保GUI在运行时不会卡住),但是我无法在Qt.Thread里面启动4个新线程来处理文件列表。
这是我的核心代码
self.unzipThread = UnzipThread()
self.unzipThread.start()
self.unzipThread.finished.connect(self.finishUp()) #finsihUp provides the final page of the wizard
class UnzipThread(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
for dirname, dirnames, filenames in os.walk(directorypath):
for filename in filenames:
if filename.endswith(".zip"):
fileList.append(filename)
count = count +1
如果我尝试在运行函数中添加启动线程的代码,就会出现一个错误,提示这是不被允许的。
那我该怎么做才能实现这个功能呢?
谢谢
编辑##
完整示例
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
import os
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
runButton = QtGui.QPushButton("Run")
runButton.clicked.connect(self.unzip)
exitButton = QtGui.QPushButton("Exit")
exitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(runButton)
hbox.addStretch(1)
hbox.addWidget(exitButton)
titleBox = QtGui.QVBoxLayout()
titleLabel = QtGui.QLabel(self.tr("Find Zip File"))
searchBox = QtGui.QHBoxLayout()
self.fileLabel = QtGui.QLabel(self.tr("Location: "))
self.fileLineEdit = QtGui.QLineEdit()
self.fileDialogBtn = QtGui.QPushButton("Browse")
self.fileDialogBtn.clicked.connect(self.openDirectoryDialog)
searchBox.addWidget(self.fileLabel)
searchBox.addWidget(self.fileLineEdit)
searchBox.addWidget(self.fileDialogBtn)
titleBox.addWidget(titleLabel)
titleBox.addStretch(1)
titleBox.addLayout(searchBox)
titleBox.addStretch(1)
titleBox.addLayout(hbox)
self.setLayout(titleBox)
self.resize(500, 300)
self.center()
self.setWindowTitle('Example')
self.show()
def unzip(self):
self.unzipThread = UnzipThread(self.filePath)
self.unzipThread.start()
self.unzipThread.finished.connect(self.finishUp)
def openDirectoryDialog(self):
flags = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly
directory = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", os.getcwd(),flags)
self.fileLineEdit.setText(directory)
self.filePath = self.fileLineEdit.text()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
def finishUp(self):#yet to code up to GUI log windows
print "finished"
class UnzipThread(QtCore.QThread):
def __init__(self, filepath):
QtCore.QThread.__init__(self)
self.filePath = filepath
def run(self):
fileList = []
count = 0
for dirname, dirnames, filenames in os.walk(self.filePath):
for filename in filenames:
if filename.endswith(".shp"):
fileList.append(filename)
count += 1
print count
list1 = []
list2 = []
for shpfile in fileList:
if "line" in shpfile:
list1.append(shpfile)
elif "point" in shpfile:
list2.append(shpfile)
else:
pass
self.processThread1 = ProcessThread1(list1)
self.processThread1.start()
self.processThread1.finished.connect(self.threadCount)
self.processThread2 = ProcessThread2(list2)
self.processThread2.start()
self.processThread2.finished.connect(self.threadCount)
return
def threadCount(self):
print "got here"
class ProcessThread1(QtCore.QThread):
def __init__(self, filelist):
QtCore.QThread.__init__(self)
self.filelist = filelist
def run(self):
count = 0
for textfile in self.filelist:
count +=1
print "thread 1 count %s" %(count)
return
class ProcessThread2(QtCore.QThread):
def __init__(self, filelist):
QtCore.QThread.__init__(self)
self.filelist = filelist
def run(self):
count = 0
for textfile in self.filelist:
count +=1
print "thread 2 count %s" %(count)
return
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
在我删掉很多代码以提供这个示例后,发现从我的QT.Thread内部运行线程是可以的,但初始线程在其他线程还没完成之前就认为自己已经结束了。
所以我得到的结果是这样的:
5635
finishedthread 1 count 2858
thread 2 count 2777here
here
你可以看到“finished”这个评论出现在其他代码“thread count 1”等之前,这证明它认为自己已经完成了。
那么,有什么办法让它们之间进行沟通吗?
谢谢
编辑 2
现在我已经把代码改成使用QObjects和movetoThread,但我该如何正确判断两个子线程是否都已经完成呢?这是我现在的代码。我不得不使用一个线程计数器和一个While循环来判断两个子线程是否都完成了。难道没有更好的方法吗?
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sys
from PySide import QtGui, QtCore
import os
from PySide.QtCore import Signal as pyqtSignal
import time
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
runButton = QtGui.QPushButton("Run")
runButton.clicked.connect(self.unzip)
exitButton = QtGui.QPushButton("Exit")
exitButton.clicked.connect(QtCore.QCoreApplication.instance().quit)
hbox = QtGui.QHBoxLayout()
hbox.addWidget(runButton)
hbox.addStretch(1)
hbox.addWidget(exitButton)
titleBox = QtGui.QVBoxLayout()
titleLabel = QtGui.QLabel(self.tr("Find Zip File"))
searchBox = QtGui.QHBoxLayout()
self.fileLabel = QtGui.QLabel(self.tr("Location: "))
self.fileLineEdit = QtGui.QLineEdit()
self.fileDialogBtn = QtGui.QPushButton("Browse")
self.fileDialogBtn.clicked.connect(self.openDirectoryDialog)
searchBox.addWidget(self.fileLabel)
searchBox.addWidget(self.fileLineEdit)
searchBox.addWidget(self.fileDialogBtn)
titleBox.addWidget(titleLabel)
titleBox.addStretch(1)
titleBox.addLayout(searchBox)
titleBox.addStretch(1)
titleBox.addLayout(hbox)
self.setLayout(titleBox)
self.resize(500, 300)
self.center()
self.setWindowTitle('Example')
self.show()
def unzip(self):
thread = self.thread = QtCore.QThread()
worker = self.worker = Worker(self.filePath)
worker.moveToThread(thread)
worker.finished.connect(worker.deleteLater)
worker.finished.connect(thread.quit)
thread.started.connect(worker.run)
thread.finished.connect(self.finishUp)
thread.start()
def openDirectoryDialog(self):
flags = QtGui.QFileDialog.DontResolveSymlinks | QtGui.QFileDialog.ShowDirsOnly
directory = QtGui.QFileDialog.getExistingDirectory(self, "Open Directory", os.getcwd(),flags)
self.fileLineEdit.setText(directory)
self.filePath = self.fileLineEdit.text()
def center(self):
qr = self.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
def closeEvent(self, event):
reply = QtGui.QMessageBox.question(self, 'Message',
"Are you sure to quit?", QtGui.QMessageBox.Yes |
QtGui.QMessageBox.No, QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
event.accept()
else:
event.ignore()
def finishUp(self):#yet to code up to GUI log windows
print "unzip thread finished"
class Worker(QtCore.QObject):
finished = pyqtSignal()
def __init__(self, filepath):
QtCore.QObject.__init__(self)
self.filePath = filepath
def run(self):
self.threadcount = 0
print "finding files"
fileList = []
count = 0
for dirname, dirnames, filenames in os.walk(self.filePath):
for filename in filenames:
if filename.endswith(".shp"):
fileList.append(filename)
count += 1
print count
self.list1 = []
self.list2 = []
for shpfile in fileList:
if "line" in shpfile:
self.list1.append(shpfile)
elif "point" in shpfile:
self.list2.append(shpfile)
else:
pass
thread1 = self.thread1 = QtCore.QThread()
worker1 = self.worker1 = Process1(self.list1)
worker1.moveToThread(thread1)
worker1.finished.connect(worker1.deleteLater)
worker1.finished.connect(thread1.quit)
thread1.started.connect(worker1.run)
thread1.finished.connect(self.finishUp)
thread1.start()
thread2 = self.thread2 = QtCore.QThread()
worker2 = self.worker2 = Process2(self.list2)
worker2.moveToThread(thread2)
worker2.finished.connect(worker2.deleteLater)
worker2.finished.connect(thread2.quit)
thread2.started.connect(worker2.run)
thread2.finished.connect(self.finishUp)
thread2.start()
def finishUp(self):
self.threadcount += 1
while True:
if self.threadcount != 2:
break
else:
print "extra threads finished"
self.finished.emit()
break
class Process1(QtCore.QObject):
finished = pyqtSignal()
def __init__(self, filelist):
QtCore.QObject.__init__(self)
self.filelist = filelist
def run(self):
count = 0
for textfile in self.filelist:
count +=1
print "thread 1 count %s" %(count)
self.finished.emit()
class Process2(QtCore.QObject):
finished = pyqtSignal()
def __init__(self, filelist):
QtCore.QObject.__init__(self)
self.filelist = filelist
def run(self):
count = 0
for textfile in self.filelist:
count +=1
time.sleep(15)
print "thread 2 count %s" %(count)
self.finished.emit()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
1 个回答
首先,"finished"这个提示出现在"thread count x"之前,是因为UnzipThread确实在ProcessingThreads之前就完成了。这是正常的情况。
其次,我不能确定是否存在通信问题,但你最好了解一下QThreads的正确使用方法。不推荐直接继承QThread,因为这样会导致信号传递的问题。更好的做法是使用工作对象,并通过QObject:movetoThread()
把它们移动到线程中。
如果你还有疑问,可以在所有可能的地方打印QThread.currentThread()
,看看实际是哪个线程在运行什么代码。