Python:如何将参数传递给线程作业(回调)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python:如何将参数传递给线程作业(回调)相关的知识,希望对你有一定的参考价值。

我在Python中使用回调实现线程。我有问题不知道如何将参数传递给线程作业。

我做了什么:

import time
import threading


class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.callback_args = callback_args

    def target_with_callback(self):
        self.method()
        if self.callback is not None:
            self.callback(*self.callback_args)


def my_thread_job(param1, param2):
    # do any things here
    print "{} {}".format(param1, param2)
    print "thread start successfully and sleep for 5 seconds"
    time.sleep(5)
    print "thread ended successfully!"


def cb(param1, param2):
    # this is run after your thread end
    print "callback function called"
    print "{} {}".format(param1, param2)


# example using BaseThread with callback
thread = BaseThread(
    name='test',
    target=my_thread_job,
    args=("test","callback"),
    callback=cb,
    callback_args=("hello", "world")
)

thread.start()

我收到了错误

回溯(最近一次调用最后一次):文件“/usr/lib64/python2.7/threading.py”,第804行,在__bootstrap_inner self.run()文件“/usr/lib64/python2.7/threading.py”中,第757行,在run self .__ target(* self .__ args,** self .__ kwargs)TypeError:target_with_callback()只取1个参数(给定5个)

任何建议表示赞赏。

答案

Original GitHub Code 这将允许您将初始参数传递给线程。

import time
import threading


class BaseThread(threading.Thread):
    def __init__(self, callback=None, callback_args=None, *args, **kwargs):
        target = kwargs.pop('target')
        target_args = kwargs.pop('target_args')
        super(BaseThread, self).__init__(target=self.target_with_callback, *args, **kwargs)
        self.callback = callback
        self.method = target
        self.method_args = target_args
        self.callback_args = callback_args

    def target_with_callback(self):
        self.method(*self.method_args)
        if self.callback is not None:
            self.callback(*self.callback_args)


def my_thread_job(param1, param2):
    # do any things here
    print "{} {}".format(param1, param2)
    print "thread start successfully and sleep for 5 seconds"
    time.sleep(5)
    print "thread ended successfully!"


def cb(param1, param2):
    # this is run after your thread end
    print "callback function called"
    print "{} {}".format(param1, param2)


# example using BaseThread with callback
thread = BaseThread(
    name='test',
    target=my_thread_job,
    target_args=("threadJobArg1","threadJobArg2"),
    callback=cb,
    callback_args=("hello", "world")
)

thread.start()

以上是关于Python:如何将参数传递给线程作业(回调)的主要内容,如果未能解决你的问题,请参考以下文章

将额外参数传递给 usort 回调

如何将正则表达式参数传递给 PHP 中的 preg 替换回调?

Prettyphoto - 如何将唯一参数传递给回调函数

有没有办法将参数传递给Runnable? [复制]

如何将回调作为参数传递给另一个函数

jquery动画回调 - 如何将参数传递给回调