time.sleep()需要保持QThread响应?

时间:2013-02-02 19:32:26

标签: python matplotlib pyqt4 qthread blit

首先,我是Python新手。我是MatLab的长期用户(工程师,而不是计算机科学家),我开始尝试将Python,NumPy,SciPy等工作到我的工作流程中。所以,请原谅我对这种精彩编程语言的明显无知!

作为我的第一次努力,我决定构建一个与我正在开发的传感器进行交互的应用程序。传感器具有微秒级分辨率(每500微秒512个高能量和512个低能量“像素”),但I / O将被阻塞。由于我将不断轮询设备,我知道线程对于保持GUI响应非常重要(GUI最终还会集成与其他设备的串行通信,并具有对传感器数据进行操作的图像处理子程序)。我创建了一个MatPlotLib的线程实例来绘制来自传感器的这些“实时”数据。虽然我已经构建了独立与传感器通信的模块并验证了我知道如何在Python中实现这一点,但我从这里简单地通过生成512个8到12之间的随机数来实现数据的“模拟”以获得低能量对于高能量“像素”,“像素”和在90和110之间的512个随机数。那是线程化的。通过这里的许多例子,我还学会了使用blitting来使用MatPlotLib获得足够快的屏幕更新 - 但问题是,除非我使用time.sleep(0.02)使用线程进程休眠20ms,GUI是反应迟钝。这可以验证,因为来自MatPlotLib的交互式X,Y数据点反馈不起作用,并且“STOP”按钮不能用于中断该过程。任何超过time.sleep(0.02)的内容都会使GUI操作更加平滑,但代价是“数据速率”。任何比time.sleep(0.02)慢的东西都会使GUI无响应。我不确定我明白为什么。我本来打算尝试使用GUIqwt,但我想在放弃MatPlotLib之前会问这里,因为我不确定这是不是问题。我担心让线程休眠20ms将意味着我错过了传感器阵列中至少40条潜在的数据线(40行* 500us /线= 20ms)。

以下是当前代码:

import time, random, sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class ApplicationWindow(QMainWindow):

    def __init__(self, parent = None):

        QMainWindow.__init__(self, parent)

        self.thread = Worker()

        self.create_main_frame()
        self.create_status_bar()

        self.connect(self.thread, SIGNAL("finished()"), self.update_UI)
        self.connect(self.thread, SIGNAL("terminated()"), self.update_UI)       
        self.connect(self.startButton, SIGNAL("clicked()"), self.start_acquisition)       
        self.connect(self.stopButton, SIGNAL("clicked()"), self.stop_acquisition)
        self.thread.pixel_list.connect(self.update_figure)

    def create_main_frame(self):
        self.main_frame = QWidget()

        self.dpi = 100
        self.width = 10
        self.height = 8
        self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)               
        self.axes.axis((0,512,0,120))

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.canvas.updateGeometry()    
        self.canvas.draw()
        self.background = None

        self.lE_line, = self.axes.plot(range(512), [0 for i in xrange(512)], animated=True)
        self.hE_line, = self.axes.plot(range(512), [0 for i in xrange(512)], animated=True)          

        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        self.startButton = QPushButton(self.tr("&Start"))
        self.stopButton = QPushButton(self.tr("&Stop"))

        layout = QGridLayout()
        layout.addWidget(self.canvas, 0, 0)
        layout.addWidget(self.mpl_toolbar, 1, 0)
        layout.addWidget(self.startButton, 2, 0)       
        layout.addWidget(self.stopButton, 2, 1)

        self.main_frame.setLayout(layout)
        self.setCentralWidget(self.main_frame)

        self.setWindowTitle(self.tr("XRTdev Interface"))

    def create_status_bar(self):
        self.status_text = QLabel("I am a status bar.  I need a status to show!")
        self.statusBar().addWidget(self.status_text, 1)

    def start_acquisition(self):
        self.thread.exiting = False
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.thread.render()

    def stop_acquisition(self):
        self.thread.exiting = True
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.cleanup_UI()

    def update_figure(self, lE, hE):
        if self.background == None:
            self.background = self.canvas.copy_from_bbox(self.axes.bbox)
        self.canvas.restore_region(self.background)
        self.lE_line.set_ydata(lE)
        self.hE_line.set_ydata(hE)
        self.axes.draw_artist(self.lE_line)
        self.axes.draw_artist(self.hE_line)
        self.canvas.blit(self.axes.bbox)

    def update_UI(self):
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.cleanup_UI()        

    def cleanup_UI(self):
        self.background = None
        self.axes.clear()        
        self.canvas.draw()

class Worker(QThread):

    pixel_list = pyqtSignal(list, list)

    def __init__(self, parent = None):
        QThread.__init__(self, parent)
        self.exiting = False

    def __del__(self):
        self.exiting = True
        self.wait()

    def render(self):
        self.start()

    def run(self):
        # simulate I/O
        n = random.randrange(100,200)
        while not self.exiting and n > 0:
            lE = [random.randrange(5,16) for i in xrange(512)]
            hE = [random.randrange(80,121) for i in xrange(512)]
            self.pixel_list.emit(lE, hE)
            time.sleep(0.02)
            n -= 1

def main():
    app = QApplication(sys.argv)
    form = ApplicationWindow()
    form.show()
    app.exec_()

if __name__ == "__main__":
    main()

也许我的问题甚至不是MatPlotLib或PyQT4,而是我实现线程的方式。正如我所说,我是新手,并且正在学习。而且,我甚至不确定GUIqwt会解决任何这些问题 - 但我知道我在这里看到很多建议使用比MatPlotLib更快的东西用于GUI中的“实时”绘图。感谢您的帮助!

1 个答案:

答案 0 :(得分:3)

[编辑因为QThread令人困惑/困惑]

似乎有两种方法可以使用它,或者对它进行子类化(如示例和文档所述),或者创建一个worker对象,然后将其移动到一个线程(参见this blog post)。当你混合信号/插槽时,我会更加困惑。正如Avaris所说,这种改变可能不是你的问题。

我将Worker课程重新设为QObject的子课程(因为这是我理解的风格)。

问题在于,如果您没有在假数据系统中放置sleep,那么您将生成所有回调到主窗口的< 1秒。然后,主线程基本上被阻塞,因为它清除了信号队列。如果你将延迟设置为你指定的延迟(0.0005s),那么它通过生成数据的速度远远超过它可以显示的速度,这似乎表明这可能不适合你的问题(务实,你也可以看得那么快,似乎在30 - 40 fps时没问题。

import time, random, sys
#from PySide.QtCore import *
#from PySide.QtGui import *

from PyQt4 import QtCore
from PyQt4 import QtGui

from matplotlib.figure import Figure
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas

class ApplicationWindow(QtGui.QMainWindow):
    get_data = QtCore.pyqtSignal()

    def __init__(self, parent = None):

        QtGui.QMainWindow.__init__(self, parent)


        self.thread = QtCore.QThread(parent=self)
        self.worker = Worker(parent=None)
        self.worker.moveToThread(self.thread)

        self.create_main_frame()
        self.create_status_bar()

        self.startButton.clicked.connect(self.start_acquisition) 
        self.stopButton.clicked.connect(self.stop_acquisition)
        self.worker.pixel_list.connect(self.update_figure)
        self.worker.done.connect(self.update_UI)

        self.get_data.connect(self.worker.get_data)


        self.thread.start()


    def create_main_frame(self):
        self.main_frame = QtGui.QWidget()

        self.dpi = 100
        self.width = 10
        self.height = 8
        self.fig = Figure(figsize=(self.width, self.height), dpi=self.dpi)
        self.axes = self.fig.add_subplot(111)               
        self.axes.axis((0,512,0,120))

        self.canvas = FigureCanvas(self.fig)
        self.canvas.setParent(self.main_frame)
        self.canvas.updateGeometry()    
        self.canvas.draw()
        self.background = None

        self.lE_line, = self.axes.plot(range(512), [0 for i in xrange(512)], animated=True)
        self.hE_line, = self.axes.plot(range(512), [0 for i in xrange(512)], animated=True)          

        self.mpl_toolbar = NavigationToolbar(self.canvas, self.main_frame)

        self.startButton = QtGui.QPushButton(self.tr("&Start"))
        self.stopButton = QtGui.QPushButton(self.tr("&Stop"))

        layout = QtGui.QGridLayout()
        layout.addWidget(self.canvas, 0, 0)
        layout.addWidget(self.mpl_toolbar, 1, 0)
        layout.addWidget(self.startButton, 2, 0)       
        layout.addWidget(self.stopButton, 2, 1)

        self.main_frame.setLayout(layout)
        self.setCentralWidget(self.main_frame)

        self.setWindowTitle(self.tr("XRTdev Interface"))

    def create_status_bar(self):
        self.status_text = QtGui.QLabel("I am a status bar.  I need a status to show!")
        self.statusBar().addWidget(self.status_text, 1)

    def start_acquisition(self):
        self.worker.exiting = False
        self.startButton.setEnabled(False)
        self.stopButton.setEnabled(True)
        self.get_data.emit()

    def stop_acquisition(self):
        self.worker.exiting = True
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.cleanup_UI()

    def update_figure(self, lE, hE):
        if self.background == None:
            self.background = self.canvas.copy_from_bbox(self.axes.bbox)
        self.canvas.restore_region(self.background)
        self.lE_line.set_ydata(lE)
        self.hE_line.set_ydata(hE)
        self.axes.draw_artist(self.lE_line)
        self.axes.draw_artist(self.hE_line)
        self.canvas.blit(self.axes.bbox)

    def update_UI(self):
        self.startButton.setEnabled(True)
        self.stopButton.setEnabled(False)
        self.cleanup_UI()        

    def cleanup_UI(self):
        self.background = None
        self.axes.clear()        
        self.canvas.draw()

class Worker(QtCore.QObject):

    pixel_list = QtCore.pyqtSignal(list, list)
    done = QtCore.pyqtSignal()

    def __init__(self, parent = None):
        QtCore.QObject.__init__(self, parent)
        self.exiting = True

    @QtCore.pyqtSlot()
    def get_data(self):
        # simulate I/O
        print 'data_start'
        n = random.randrange(100,200)
        while not self.exiting and n > 0:
            lE = [random.randrange(5,16) for i in xrange(512)]
            hE = [random.randrange(80,121) for i in xrange(512)]
            self.pixel_list.emit(lE, hE)
            time.sleep(0.05)
            n -= 1
        print 'n: ', n
        self.done.emit()