简体   繁体   中英

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM