@Needs cleanup
Note: Uses the Python 3.5+ async/await syntax
asyncio supports the use of Executor objects found in concurrent.futures for scheduling tasks asynchronously. Event loops have the function run_in_executor() which takes an Executor object, a Callable, and the Callable’s parameters.
Scheduling a task for an Executor
import asyncio
from concurrent.futures import ThreadPoolExecutor
def func(a, b):
return a + b
async def main(loop):
executor = ThreadPoolExecutor() result = await loop.run_in_executor(executor, func, “Hello,”, “ world!”) print(result)
if __name__ == "__main__":
loop = asyncio.get_event_loop() loop.run_until_complete(main(loop))
Each event loop also has a “default” Executor slot that can be assigned to an Executor. To assign an Executor and schedule tasks from the loop you use the set_default_executor() method.
import asyncio
from concurrent.futures import ThreadPoolExecutor
def func(a, b):
return a + b
async def main(loop):
None as the first parameter designates the default Executor.result = await loop.run_in_executor(None, func, “Hello,”, “ world!”) print(result)
if __name__ == "__main__":