gpt4 book ai didi

python - 如何在 pyqt 中同时运行 2 个线程?

转载 作者:太空宇宙 更新时间:2023-11-03 15:41:40 25 4
gpt4 key购买 nike

我试图使用 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_())

最佳答案

也许thread2的方法run必须调用updateProgressBar2,而不是updateProgressBar?

关于python - 如何在 pyqt 中同时运行 2 个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42062711/

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