我有一个Python脚本会产生许多异步请求.我正在使用的API进行回调.
我可以在Python 2.7中使用什么来实现这一目标?
def run():
for request in requests:
client.send_request(request,callback)
def callback(error,response):
# handle response
pass
def main():
run()
# I want to block here
最佳答案
我发现最简单,侵入性最小的方法是使用threading.Event,available in 2.7.
原文链接:https://www.f2er.com/python/438595.htmlimport 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)