Python中的异步方法调用?

2024-05-20 13:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道Python中是否有用于异步方法调用的库。如果你能做些

@async
def longComputation():
    <code>


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

或异步调用非异步例程

def longComputation()
    <code>

token = asynccall(longComputation())

如果能有一个更精细的策略作为语言核心的母语,那就太好了。考虑过了吗?


Tags: 方法tokenasyncdefcallbacknotcodefunction
3条回答

从Python3.5开始,您可以为异步函数使用增强的生成器。

import asyncio
import datetime

增强的生成器语法:

@asyncio.coroutine
def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        yield from asyncio.sleep(1)


loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

新的async/await语法:

async def display_date(loop):
    end_time = loop.time() + 5.0
    while True:
        print(datetime.datetime.now())
        if (loop.time() + 1.0) >= end_time:
            break
        await asyncio.sleep(1)


loop = asyncio.get_event_loop()
# Blocking call which returns when the display_date() coroutine is done
loop.run_until_complete(display_date(loop))
loop.close()

您可以使用Python 2.6中添加的multiprocessing module。您可以使用进程池,然后使用以下方法异步获取结果:

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.

这只是一种选择。这个模块提供了很多工具来实现您想要的。而且,用这个做一个装饰师也很容易。

类似于:

import threading

thr = threading.Thread(target=foo, args=(), kwargs={})
thr.start() # Will run "foo"
....
thr.is_alive() # Will return whether foo is running currently
....
thr.join() # Will wait till "foo" is done

有关详细信息,请参阅https://docs.python.org/library/threading.html上的文档。

相关问题 更多 >