I have a Python script makes many async requests. The API I'm using takes a callback.
The main function calls run and I want it to block execution until all the requests have come back.
What could I use within Python 2.7 to achieve this?
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
I found that the simplest, least invasive way is to use 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With