Asynchronous method call in Python? Asynchronous method call in Python? python python

Asynchronous method call in Python?


Something like:

import threadingthr = 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

See the documentation at https://docs.python.org/library/threading.html for more details.


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]]])

E.g.:

from multiprocessing import Pooldef f(x):    return x*xif __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.


As of Python 3.5, you can use enhanced generators for async functions.

import asyncioimport datetime

Enhanced generator syntax:

@asyncio.coroutinedef 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 doneloop.run_until_complete(display_date(loop))loop.close()

New async/await syntax:

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 doneloop.run_until_complete(display_date(loop))loop.close()