gpt4 book ai didi

python - 将 PyQt 与 gevent 结合使用

转载 作者:太空狗 更新时间:2023-10-29 20:19:19 25 4
gpt4 key购买 nike

有人在 gevent 上使用过 PyQt 吗?如何将 PyQt 循环链接到 gevent?

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

最佳答案

您可以使用 Qt IDLE“计时器”来允许 gevent 处理其微线程,同时在短时间内(例如 10 毫秒)没有处理任何 Qt 事件。它仍然不完美,因为它没有提供“最平滑”的可能集成。这是因为我们没有为 Qt 和 gevent 使用单一的事件循环,只是及时地“交错”它们。

正确的解决方案是允许 libevent 以某种方式监听新的 Qt 事件,但我还没有弄清楚如何在实践中做到这一点。也许让 Qt 在 GUI 事件到达事件队列时通过套接字向 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()

关于python - 将 PyQt 与 gevent 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4628348/

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