Python 如何在pyqt中同时运行两个线程?
我试图使用pyqt和线程同时读取两个不同的文件,但两个线程中只有一个线程被耗尽。我的代码有两个线程类,每个线程类负责读取分配给它们的文件。我怎样才能做到这一点 以下是我尝试过的:Python 如何在pyqt中同时运行两个线程?,python,python-2.7,pyqt4,Python,Python 2.7,Pyqt4,我试图使用pyqt和线程同时读取两个不同的文件,但两个线程中只有一个线程被耗尽。我的代码有两个线程类,每个线程类负责读取分配给它们的文件。我怎样才能做到这一点 以下是我尝试过的: import sys from PyQt4 import QtCore, QtGui import subprocess from time import sleep class Thread1(QtCore.QThread): def __init__(self): QtCore.QThre
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_())
也许thread2的方法运行必须调用updateProgressBar2,而不是updateProgressBar?谢谢,你说得对。很抱歉问了这么愚蠢的问题。