[Python] threadpool1.2.7回调函数的参数设置

  经常用到threadpool这个库,用起来很简单:

  

        pool = threadpool.ThreadPool(threadnum)
        reqs = threadpool.makeRequests(repeater.get_rq, args_list=arg_list, callback=result_handle_func)
        [pool.putRequest(req) for req in reqs]
        pool.wait()
        pool.dismissWorkers(threadnum)

  如上,是最经典的调用方法,关键在第二句,在这里我经常遇到问题,特别是参数的问题。如果是单个的参数,那么很简单,这里的args_list只需要是个列表,里面是所有参数即可。

  但是情况不总是那么简单,比如,我的repeater.get_rq函数是这样的:

    @staticmethod
    def get_rq(*opt):
        '''
        :param opt: 字典包括了 url   want ,前者是url,后者是body 或者header
        :return:
        '''
        opt = opt[0]
        if opt == {}:
            return "Not a Lucky day?ah?"

        url = opt["url"]
        want = opt["want"]
        cookies = None
        if 'cookies' in opt.keys():
            cookies = opt['cookies']
        url = urlinfo(url).url
        header = getrandomheader()
        if cookies:
            rq = requests.get(url, headers=header,cookies=cookies)
        else:
            rq = requests.get(url, headers=header)
        if want=="body":
            return rq.text
        else:
            return rq.headers

我希望这样使用这个函数:

    temp = {
        "url":"www.wooyun.org",
        "want":"body",
    }
    a = repeater.get_rq(temp)

看起来这里用了个*很多余,其实就是为了适配threadpool函数。

看threadpool代码可以知道,如果你的参数不是元组,那么会封装为列表再传参。此时,你的回调函数接收到的参数为:

[你的参数],None

然后threadpool会这样调用:

result = request.callable(*request.args, **request.kwds)

前一个就是你的参数。

posted @ 2015-05-13 13:57  mhxzkhl  阅读(708)  评论(0编辑  收藏  举报