有人使用pyqt和gevent吗?如何将pyqt循环链接到gevent?

http://www.gevent.org/ - 基于Coroutine的Python Networking库,该库使用Greenlet在Libevent事件循环之上提供高级同步API。

有帮助吗?

解决方案

其他提示

您可以使用QT空闲“计时器”来允许 gevent 为了处理其微读,而没有QT事件在短时间内处理,例如10毫秒。它仍然不是完美的,因为它没有给出“最平稳的”可能集成。这是因为我们不为QT和Gevent使用单个事件循环,只是在及时“交织”它们。

正确的解决方案是允许Libevent以某种方式聆听新的QT事件,但是我还没有在实践中弄清楚如何做到这一点。当GUI事件到达活动队列会有所帮助时,也许让QT通过插座将某些东西发送给Gevent。有人解决了吗?

工作示例:

""" Qt - gevent event loop integration using a Qt IDLE timer
"""

import sys, itertools

import PySide
from PySide import QtCore, QtGui

import gevent

# Limit the IDLE handler's frequency while still allow for gevent
# to trigger a microthread anytime
IDLE_PERIOD = 0.01

class MainWindow(QtGui.QMainWindow):

    def __init__(self, application):

        QtGui.QMainWindow.__init__(self)

        self.application = application

        self.counter = itertools.count()

        self.resize(400, 100)
        self.setWindowTitle(u'Counting: -')

        self.button = QtGui.QPushButton(self)
        self.button.setText(u'Reset')
        self.button.clicked.connect(self.reset_counter)

        self.show()

    def counter_loop(self):

        while self.isVisible():
            self.setWindowTitle(u'Counting: %d' % self.counter.next())
            gevent.sleep(0.1)

    def reset_counter(self):

        self.counter = itertools.count()

    def run_application(self):

        # IDLE timer: on_idle is called whenever no Qt events left for processing
        self.timer = QtCore.QTimer()
        self.timer.timeout.connect(self.on_idle)
        self.timer.start(0)

        # Start counter
        gevent.spawn(self.counter_loop)

        # Start you application normally, but ensure that you stop the timer
        try:
            self.application.exec_()
        finally:
            self.timer.stop()

    def on_idle(self):

        # Cooperative yield, allow gevent to monitor file handles via libevent
        gevent.sleep(IDLE_PERIOD)

def main():

    application = QtGui.QApplication(sys.argv)
    main_window = MainWindow(application)
    main_window.run_application()

if __name__ == '__main__':
    main()

我尝试了以下方法:为Gevent拥有“ PYQT后端”,即。使用PYQT构建体(例如QSocketNotifier,QTimer等)而不是LIBEV循环的GEVENT循环的实现。最后,我发现比做相反的情况要容易得多,而且性能非常好(QT的循环基于Linux下的GLIB,还不错)。

这是GitHub上有关感兴趣的人的项目的链接:https://github.com/mguijarr/qtgevent

这只是一个开始,但是它对我所做的测试效果很好。如果在GEVENT和PYQT方面拥有更多经验的人可以做出贡献,我会很高兴。

您应该避免使用app.exec_(),这是一个循环函数,它使用此函数来处理事件:

http://doc.qt.nokia.com/stable/qcoreapplication.html#processevents

因此,您可以直接调用ProcessEvents。

我发布了一个名为的项目 Eventlet-pyqt. 。我希望这对于想要在PYQT应用程序中使用Greenlet的人可能很有用。我也尝试了gevent,但是由于我的C语言经验不佳,我很难为libevent编写插件。主要问题使用 QApplicaton::processEvents() 或零间隙 QTimer IS,该程序陷入无限循环,导致100%CPU核心使用情况。为了避免这种情况,我写了一个新的枢纽来替换 select() pyqt的功能 QSocketNotifier. 。希望此消息可以帮助某些人。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top