【问题标题】:How to pass parameters to PyQt QThreadPool running function如何将参数传递给 PyQt QThreadPool 运行函数
【发布时间】:2020-02-08 04:31:35
【问题描述】:

关于此代码的问题:Multithreading PyQt applications with QThreadPool

从下面的代码中,如何将附加参数从oh_no 函数传递给execute_this_fn

如果我直接传递类似的参数:

worker = Worker(self.execute_this_fn(arg1, arg2))

并照常接受:

def execute_this_fn(self, progress_callback, a ,b):

我收到一个错误:

result = self.fn(*self.args, **self.kwargs) 类型错误: execute_this_fn() 获得了参数“progress_callback”的多个值

甚至有评论告诉“路径任何 args 和 kwargs 来运行函数”但是正确的语法是什么?

文章中的可执行代码:

from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

import time
import traceback, sys


class WorkerSignals(QObject):
    '''
    Defines the signals available from a running worker thread.

    Supported signals are:

    finished
        No data

    error
        `tuple` (exctype, value, traceback.format_exc() )

    result
        `object` data returned from processing, anything

    progress
        `int` indicating % progress 

    '''
    finished = pyqtSignal()
    error = pyqtSignal(tuple)
    result = pyqtSignal(object)
    progress = pyqtSignal(int)


class Worker(QRunnable):
    '''
    Worker thread

    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

    :param callback: The function callback to run on this worker thread. Supplied args and 
                     kwargs will be passed through to the runner.
    :type callback: function
    :param args: Arguments to pass to the callback function
    :param kwargs: Keywords to pass to the callback function

    '''

    def __init__(self, fn, *args, **kwargs):
        super(Worker, self).__init__()

        # Store constructor arguments (re-used for processing)
        self.fn = fn
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()    

        # Add the callback to our kwargs
        self.kwargs['progress_callback'] = self.signals.progress        

    @pyqtSlot()
    def run(self):
        '''
        Initialise the runner function with passed args, kwargs.
        '''

        # Retrieve args/kwargs here; and fire processing using them
        try:
            result = self.fn(*self.args, **self.kwargs)
        except:
            traceback.print_exc()
            exctype, value = sys.exc_info()[:2]
            self.signals.error.emit((exctype, value, traceback.format_exc()))
        else:
            self.signals.result.emit(result)  # Return the result of the processing
        finally:
            self.signals.finished.emit()  # Done



class MainWindow(QMainWindow):


    def __init__(self, *args, **kwargs):
        super(MainWindow, self).__init__(*args, **kwargs)

        self.counter = 0

        layout = QVBoxLayout()

        self.l = QLabel("Start")
        b = QPushButton("DANGER!")
        b.pressed.connect(self.oh_no)

        layout.addWidget(self.l)
        layout.addWidget(b)

        w = QWidget()
        w.setLayout(layout)

        self.setCentralWidget(w)

        self.show()

        self.threadpool = QThreadPool()
        print("Multithreading with maximum %d threads" % self.threadpool.maxThreadCount())

        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.recurring_timer)
        self.timer.start()

    def progress_fn(self, n):
        print("%d%% done" % n)

    def execute_this_fn(self, progress_callback):
        for n in range(0, 5):
            time.sleep(1)
            progress_callback.emit(n*100/4)

        return "Done."

    def print_output(self, s):
        print(s)

    def thread_complete(self):
        print("THREAD COMPLETE!")

    def oh_no(self):
        # Pass the function to execute
        worker = Worker(self.execute_this_fn) # Any other args, kwargs are passed to the run function
        worker.signals.result.connect(self.print_output)
        worker.signals.finished.connect(self.thread_complete)
        worker.signals.progress.connect(self.progress_fn)

        # Execute
        self.threadpool.start(worker) 


    def recurring_timer(self):
        self.counter +=1
        self.l.setText("Counter: %d" % self.counter)


app = QApplication([])
window = MainWindow()
app.exec_()

【问题讨论】:

  • 好的,你明白使用 ThreadPool 和使用 QThread 的区别了吗?我问是因为它们用于非常不同的目的
  • @DennisJensen QThreadPool 为我处理排队和执行,但 QThread 需要指示排队和加入线程?
  • @eyllanesc(由于某种原因,你真的不喜欢我)最小的可执行示例,你可以在第一句的附加链接中看到
  • @NickPV 1) 我来这里不是为了社交生活,所以如果有人喜欢我,我会避免发表我的意见 2) 根据 SO 规则,MRE 必须在问题中,而不是依赖于外部资源,因为如果您提供的链接损坏,问题可能无法被理解。你现在明白我的要求了吗?

标签: python python-3.x multithreading pyqt5 threadpool


【解决方案1】:

如果您查看 Worker 类的文档,我们会发现它指出了如何建立附加参数:

class Worker(QRunnable):
    """
    Worker thread

    Inherits from QRunnable to handler worker thread setup, signals and wrap-up.

    :param callback: The function callback to run on this worker thread. Supplied args and 
                     kwargs will be passed through to the runner.
    :type callback: function
    :param args: Arguments to pass to the callback function
    :param kwargs: Keywords to pass to the callback function
    # ...

在您的情况下,您必须更改为:

worker = Worker(self.execute_this_fn, arg1, arg2)

另一方面,如果观察到以下部分源代码:

# ...
self.kwargs["progress_callback"] = self.signals.progress
# ...

从中可以看出,progress_callback 是 kwargs 的一部分,必须在 args 之后,因此您必须将代码更改为:

def execute_this_fn(self, a, b, progress_callback):

【讨论】:

    猜你喜欢
    • 2013-07-24
    • 2012-02-08
    • 1970-01-01
    • 2020-12-25
    • 2014-05-16
    • 2015-10-30
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多