How to block and wait for async, callback based Py

2019-04-29 13:52发布

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条回答
Ridiculous、
2楼-- · 2019-04-29 14:39

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)
查看更多
登录 后发表回答