PyQt:如果运行时间过长,如何使用Qthread使进程停止运行

时间:2014-12-15 21:45:36

标签: multithreading qt pyqt scipy multiprocessing

我在线程上已经阅读了很多内容,但我真的需要这方面的帮助: 我有一个PyQt主GUI,使用scipy.minimize运行优化... 我不能不举一个例子,我使用“占位符”过程 显示我的问题。

如果进程花费的时间太长,我想让主GUI仍然可以被用户停止 结果。 我的工作示例是这个,我使用与sympy的集成

import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
import time, sys
from PyQt4.QtCore  import *
from PyQt4.QtGui import *

class IntegrationRunner(QObject):
    'Object managing the integration'

    def __init__(self):
        super(IntegrationRunner, self).__init__() 
        self._isRunning = True

    def longRunning(self):      
        # reset
        if not self._isRunning:
            self._isRunning = True  

        print("preparing Integration")
        #this is known to be time consuming and returning not the right integral
        #this is a placeholder for a "time consuming" operation that sould 
        #be handled by a thread outside the main GUI
        #imagine an optimization process or any other time consuming operation
        #that would freeze the Main GUI

        t=sp.symbols('t')
        exp=sp.sqrt((3*t+1)/t)
        sol=sp.integrate(exp,t)
        print(sol)

        print('finished...') 

    def stop(self):
        self._isRunning = False
        #this is displayed when the "stop button" is clicked 
        #but actually the integration process won´t stop
        print("Integration too long - User terminated")

class SimulationUi(QDialog):
    'PyQt interface'

    def __init__(self):
        super(SimulationUi, self).__init__()

        self.goButton = QPushButton('Run Integration')
        self.stopButton = QPushButton('Stop if too long')


        self.layout = QHBoxLayout()
        self.layout.addWidget(self.goButton)
        self.layout.addWidget(self.stopButton)

        self.setLayout(self.layout)

        self.simulThread = QThread()
        self.simulThread.start()

        self.simulIntegration = IntegrationRunner()
        self.simulIntegration.moveToThread(self.simulThread)
        #self.simulIntegration.stepIncreased.connect(self.currentStep.setValue)

        # call stop on Integr.Runner from this (main) thread on click
        self.stopButton.clicked.connect(lambda: self.simulIntegration.stop())
        self.goButton.clicked.connect(self.simulIntegration.longRunning)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    simul = SimulationUi()
    simul.show()
    sys.exit(app.exec_()) 

在集成自动停止之前单击“开始”按钮和“停止”按钮 我得到了这个输出:

>>preparing Integration
>>Integration too long - User terminated
>>Integral(sqrt((3*t + 1)/t), t)
>>finished...

这不完全是我的问题,但我想了解如何使用我可以放置的线程 耗时的计算并停止它们以尝试其他“参数”或“初始猜测” 使用Scipy Minimize之类的东西 是否有可能从“外部”停止迭代功能并重新启动它而不会进入“无响应”? 任何有待改进的帮助表示赞赏。 我把这些例子作为指导 how-to-signal-from-a-running-qthread-back-to-...pastebin

0 个答案:

没有答案