11

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

1 Answer 1

9

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.