我有一个Python脚本会产生许多异步请求。我使用的API进行回调。
主函数调用run,我希望它阻止执行,直到所有请求都返回。
我可以在Python 2.7中使用什么来实现这一目标?
mod_rewrite
答案 0 :(得分:3)
我发现最简单,侵入性最小的方法是使用threading.Event
,available in 2.7。
import threading
import functools
def run():
events = []
for request in requests:
event = threading.Event()
callback_with_event = functools.partial(callback, event)
client.send_request(request, callback_with_event)
events.append(event)
return events
def callback(event, error, response):
# handle response
event.set()
def wait_for_events(events):
for event in events:
event.wait()
def main():
events = run()
wait_for_events(events)