Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python asyncio run_forever or while True

Should I replace while True in my code (without asyncio) or should I use asyncio event loop to accomplish the same result.

Currently I work on some kind "worker" that is connected to zeromq, receive some data and then performs some request (http) to external tool(server). Everything is written in normal blocking IO. Does it makes sense to use asyncio event loop to get rid of while True: ...?

In future it might be rewritten fully in asyncio, but now I'm afraid to start with asyncio.

i'm new with asyncio and not all part of this library are clear for me :)

Thx :)

like image 314
qwetty Avatar asked Sep 24 '15 12:09

qwetty


People also ask

How many times should Asyncio run () be called?

It should be used as a main entry point for asyncio programs, and should ideally only be called once. New in version 3.7.

Can you have multiple event loops in Python?

You can create multiple threads and run different event loops in each of them.

What is Asyncio Get_event_loop ()?

asyncio. get_event_loop () Get the current event loop. If there is no current event loop set in the current OS thread, the OS thread is main, and set_event_loop() has not yet been called, asyncio will create a new event loop and set it as the current one.

When should I use Asyncio Python?

asyncio is used as a foundation for multiple Python asynchronous frameworks that provide high-performance network and web-servers, database connection libraries, distributed task queues, etc. asyncio is often a perfect fit for IO-bound and high-level structured network code.


1 Answers

If you want to start writing asyncio code with a library that doesn't support it, you can use BaseEventLoop.run_in_executor.

This allows you to submit a callable to a ThreadPoolExecutor or a ProcessPoolExecutor and get the result asynchronously. The default executor is a thread pool of 5 threads.

Example:

# Python 3.4
@asyncio.coroutine
def some_coroutine(*some_args, loop=None):
    while True:
        [...]
        result = yield from loop.run_in_executor(
            None,  # Use the default executor
            some_blocking_io_call, 
            *some_args)
        [...]

# Python 3.5
async def some_coroutine(*some_args, loop=None):
    while True:
        [...]
        result = await loop.run_in_executor(
            None,  # Use the default executor
            some_blocking_io_call, 
            *some_args)
        [...]

loop = asyncio.get_event_loop()
coro = some_coroutine(*some_arguments, loop=loop)
loop.run_until_complete(coro)
like image 189
Vincent Avatar answered Sep 18 '22 22:09

Vincent