【发布时间】: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