Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block and wait for async, callback based Python function calls

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
like image 881
David Saltares Avatar asked Jul 21 '16 08:07

David Saltares


1 Answers

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)
like image 65
David Saltares Avatar answered Oct 23 '22 19:10

David Saltares