如何阻止和等待基于回调的异步,Python函数调用

前端之家收集整理的这篇文章主要介绍了如何阻止和等待基于回调的异步,Python函数调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个Python脚本会产生许多异步请求.我正在使用的API进行回调.

函数调用run,我希望它阻止执行,直到所有请求都返回.

我可以在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.

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)

猜你在找的Python相关文章