在Python异步方法调用? [英] Asynchronous method call in Python?

查看:229
本文介绍了在Python异步方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在想,如果有一个为异步方法任何一间图书馆 Python的调用。这将是巨大的,如果你可以不喜欢

I was wondering if there's any library for asynchronous method calls in Python. It would be great if you could do something like

@async
def longComputation():
    <code>


token = longComputation()
token.registerCallback(callback_function)
# alternative, polling
while not token.finished():
    doSomethingElse()
    if token.finished():
        result = token.result()

或者异步调用非异步例行

Or to call a non-async routine asynchronously

def longComputation()
    <code>

token = asynccall(longComputation())

这将是巨大的,有一个更精致的策略,如在语言核心的原生。是这样的考虑?

It would be great to have a more refined strategy as native in the language core. Was this considered?

推荐答案

您可以使用多模块在Python 2.6增加。您可以使用流程池,然后用得到的结果异步:

You can use the multiprocessing module added in Python 2.6. You can use pools of processes and then get results asynchronously with:

apply_async(func[, args[, kwds[, callback]]])

例如:

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=1)              # Start a worker processes.
    result = pool.apply_async(f, [10], callback) # Evaluate "f(10)" asynchronously calling callback when finished.

这是唯一的选择。该模块提供了大量的设施,以达到你想要的东西。此外,它会很容易使从这一个装饰。

This is only one alternative. This module provides lots of facilities to achieve what you want. Also it will be really easy to make a decorator from this.

这篇关于在Python异步方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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