【问题标题】:Using a fucntion as a parameter in a function that is meant to be run in a thread cant return将函数用作要在线程中运行的函数中的参数无法返回
【发布时间】:2021-09-04 03:38:06
【问题描述】:

我正在尝试从线程调用函数。线程函数在线程的主函数调用中将一个函数作为参数。

 Process Process-1:
Traceback (most recent call last):
  File "/usr/lib/python3.8/multiprocessing/process.py", line 315, in _bootstrap
    self.run()
  File "/usr/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
TypeError: 'dict' object is not callable

上面是我收到的错误。当我运行它时,它不在线程中,即 request_() 而不是 request() 有效,但由于某种原因,在线程中使用时它无法正确返回值。此外,如果我删除 req() 中的 return 语句,它会在线程中工作。但我想让函数的返回值用作主线程函数中的参数。任何帮助表示赞赏:)

def req():
        r = requests.get('http://url')
        return json.loads(r.content)   
    
    class limiter:
    
    
        def __init__(self, interval, allowed):
            if allowed < 1:
                exit()
            self.connections_ = 0
            self.time_created_ = time.time()
            self.request_interval_ = interval
            self.requests_allowed = allowed
    
        
    
        def request_(self, function):
            res = None
            if time.time() < (self.time_created_ + self.request_interval_):
                if self.connections_ < self.requests_allowed:
                    self.connections_ += 1
                    res = function()
                else:
                    while self.connections_ > self.requests_allowed:
                        if time.time() > (self.time_created_ + self.request_interval_):
                           break 
                        continue
                    self.connections_ += 1
                    res = function()
            
            if time.time() > (self.time_created_ + self.request_interval_):
                self.connections_ = 0
                self.time_created_ = time.time()
            return res
            
    
        
        def request(self, function):
            p1 = Process(target=self.request_(function))
            p1.start()
            p1.join()
    
    l = limiter(10, 10)
    print(l.request(req))

【问题讨论】:

    标签: python multithreading scripting


    【解决方案1】:

    您将方法的结果作为 Process 目标而不是方法本身传递。

    你想做的:

    p1 = Process(target=self.request_, args=(function,))
    

    【讨论】:

    • 行得通!谢谢 Sven .. 现在线程函数 request() 返回 None 但如果我在返回 res 之前打印出响应它具有正确的值。我不知道你是否知道这一点,但是否有可能从我尝试的线程中获取可用的返回值?
    • 是的,但不是直接来自标准的 ThreadProcess 实例。有很多方法可以实现这一目标。见How to get the return value from a thread in python?。通读这个。如果您还有任何问题,请随时再次提问。
    • 会很感激的
    • 最终在该线程的帮助下完成了 Sven.. 再次感谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-17
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    相关资源
    最近更新 更多