我试图使用pyqt和线程同时读取2个不同的文件,但只有一个线程用完了两个。我的代码有2个线程类,每个类都负责读取它们分配的文件。我怎样才能做到这一点?
以下是我尝试的内容:
import sys
from PyQt4 import QtCore, QtGui
import subprocess
from time import sleep
class Thread1(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def file_len(self):
p = subprocess.Popen(['wc', '-l', 'file1.txt'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
raise IOError(err)
return int(result.strip().split()[0]) #returns 600 lines
def run(self):
self.emit(QtCore.SIGNAL('updateProgressBar(int)'), 0) ## Reset progressbar value
file_in = "file1.txt"
loading = 0
x = float(100) / self.file_len()
with open(file_in) as f:
for line in f:
loading += x
print line
self.emit(QtCore.SIGNAL('updateProgressBar(int)'), loading)
sleep(0.15)
class Thread2(QtCore.QThread):
def __init__(self):
QtCore.QThread.__init__(self)
def file_len(self):
p = subprocess.Popen(['wc', '-l', 'file2.txt'], stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
result, err = p.communicate()
if p.returncode != 0:
raise IOError(err)
return int(result.strip().split()[0]) #returns 2500 lines
def run(self):
self.emit(QtCore.SIGNAL('updateProgressBar(int)'), 0) ## Reset progressbar value
file_in = "file2.txt"
loading = 0
x = float(100) / self.file_len()
with open(file_in) as f:
for line in f:
loading += x
print line
self.emit(QtCore.SIGNAL('updateProgressBar(int)'), loading)
sleep(0.001)
class AppView(QtGui.QDialog):
def __init__(self, parent=None):
super(AppView, self).__init__(parent)
self.resize(400, 400)
self.buttonStart = QtGui.QPushButton(self)
self.buttonStart.setText("Start")
self.buttonStart.clicked.connect(self.start)
self.progress = QtGui.QProgressBar(self)
self.progress2 = QtGui.QProgressBar(self)
verticalLayout = QtGui.QVBoxLayout(self)
verticalLayout.addWidget(self.buttonStart)
verticalLayout.addWidget(self.progress)
verticalLayout.addWidget(self.progress2)
self.progressView = Thread1()
self.progressView2 = Thread2()
self.connect(self.progressView, QtCore.SIGNAL("updateProgressBar(int)"), self.updateProgressBar)
self.connect(self.progressView2, QtCore.SIGNAL("updateProgressBar2(int)"), self.updateProgressBar2)
self.start()
def updateProgressBar(self, percent):
self.progress.setValue(percent)
def updateProgressBar2(self, percent):
self.progress2.setValue(percent)
def start(self):
self.progressView.start()
self.progressView2.start()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
appview = AppView()
appview.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
也许thread2的方法运行必须调用updateProgressBar2,而不是updateProgressBar?