使用PyQt与gevent

And*_*aev 9 python pyqt gevent

有没有人使用PyQt与gevent?如何将PyQt循环链接到gevent?

http://www.gevent.org/ - 基于coroutine的Python网络库,它使用greenlet在libevent事件循环之上提供高级同步API.

fvi*_*tor 5

您可以使用 Qt IDLE“计时器”来gevent处理其微线程,而在短时间内(例如 10 毫秒)不处理 Qt 事件。它仍然不完美,因为它没有提供“最平滑”的集成。这是因为我们没有为 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()
Run Code Online (Sandbox Code Playgroud)


tmc*_*tmc 2

以下是如何通过示例的 session1 更改 pyqt 进行协作:https://github.com/traviscline/pyqt-by-example/commit/b5d6c61daaa4d2321efe89679b1687e85892460a

  • 它很容易导致 100% CPU 负载,而没有任何有用的活动,因为您没有使用大于零的“gevent.sleep”周期。 (2认同)