【问题标题】:Python threading with PyQt as decorator使用 PyQt 作为装饰器的 Python 线程
【发布时间】:2017-01-11 07:27:38
【问题描述】:

各位溢出者,您好,这是我卡住的另一个代码。 我正在使用装饰器异步运行一些功能。

文件:async.py

from threading import Thread
from functools import wraps


def run(func):
    @wraps(func)
    def async_func(*args, **kwargs):
        func_hl = Thread(target=func, args=args, kwargs=kwargs)
        func_hl.daemon = False
        func_hl.start()
        return func_hl

    return async_func

然后:

import async

[...]

@async.run
def foo():
   while condition:
       do_something()

但现在我用 QT 和那些 QThreads 制作了一个项目。

所以,问题是:我应该如何改进我的装饰器以使其对 QT 友好? 到目前为止,我的努力是这样的:

def better_thread(to_wrap):
    class MyThread(QtCore.QThread):
        def run(self, *args, **kwargs):
            _res = to_wrap(*args, **kwargs)
            return _res

    @wraps(to_wrap)
    def async_func(*args, **kwargs):
        def finish():
            pass
        mythread = MyThread()
        mythread.start()
        result = mythread.run(*args, **kwargs)
        return result
    return async_func

我认为这是丑陋和错误的。你能帮帮我吗?

【问题讨论】:

  • Python 线程与 Qt 完美配合,你真的需要这个吗?
  • @Ceppo93 其中一些线程正在使用 gui,因此使 qt 线程成为无缝体验的首选方式。

标签: python multithreading qt pyqt qthread


【解决方案1】:

首先在这里:Threading in a PyQt application: Use Qt threads or Python threads?,提供一些常用的建议。

对代码进行简单的“重构”,使其更简洁:

class Runner(QtCore.QThread):

    def __init__(self, target, *args, **kwargs):
        super().__init__()
        self._target = target
        self._args = args
        self._kwargs = kwargs

    def run(self):
        self._target(*self._args, **self._kwargs)

def run(func):
    @wraps(func)
    def async_func(*args, **kwargs):
        runner = Runner(func, *args, **kwargs)
        # Keep the runner somewhere or it will be destroyed
        func.__runner = runner
        runner.start()

    return async_func

编辑

一个简单的测试:

@run
def test():
    sleep(1)
    print('TEST')


test()
sleep(2)
print('END')

【讨论】:

  • Ceppo93,你可能称它为安慰剂,但我真的觉得我的应用现在与 Qthread 更无缝地工作了。也非常感谢您提供保持跑步者的提示,这非常有用!
猜你喜欢
  • 1970-01-01
  • 2021-07-16
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
  • 2019-01-01
  • 1970-01-01
相关资源
最近更新 更多