问题描述
我想知道 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中的异步方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!