Python中的异步方法调用?

编程入门 行业动态 更新时间:2024-10-24 17:24:05
本文介绍了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中的异步方法调用?

本文发布于:2023-11-14 13:35:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1587356.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!