如何阻止和等待异步的,基于回调的Python函数调用 [英] How to block and wait for async, callback based Python function calls

查看:185
本文介绍了如何阻止和等待异步的,基于回调的Python函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本发出了许多异步请求。我正在使用的API会进行回调。

I have a Python script makes many async requests. The API I'm using takes a callback.

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

The main function calls run and I want it to block execution until all the requests have come back.

我可以在Python 2.7中使用什么来实现这一目标?

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


推荐答案

我发现最简单,侵入性最小的方法是使用 threading.Event 在2.7版中可用

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)

这篇关于如何阻止和等待异步的,基于回调的Python函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆