Python asyncio 的 run_forever 或 while True

5
我应该在我的代码中替换while True还是使用asyncio事件循环来实现相同的结果?
目前我正在开发一种与zeromq连接的“工作器”,接收一些数据,然后执行一些请求(http)到外部工具(服务器)。所有内容都是用正常的阻塞IO编写的。使用asyncio事件循环来摆脱while True: ...是否有意义?
将来可能会完全重写为asyncio,但现在我不敢开始使用asyncio。
我是新手,不是所有部分都很清楚:)
谢谢:)

3
如果你想尝试使用asyncio,建议你重新用aiozmq和其他支持asyncio的库完全重写程序。尝试混合使用阻塞式库和asyncio事件循环,尤其是只是为了去掉一个while True:循环,通常不是一个好主意。请注意保持原意并尽可能使翻译通俗易懂。 - dano
1个回答

12
如果您想使用不支持asyncio的库开始编写asyncio代码,可以使用BaseEventLoop.run_in_executor。这使您能够将可调用对象提交给ThreadPoolExecutorProcessPoolExecutor并异步获取结果。默认执行程序是5个线程的线程池。
例如:
# 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)

你会如何更改代码以永久运行 some_coroutine?你会选择简单的 while True: 还是其他可能的 asyncio 方式? - qwetty
2
@qwetty 在协程内部使用 while True 是完全可以的,只要你在其中执行异步调用即可。可以查看示例,例如 hello_coroutine - Vincent
1
谢谢。这正是我需要的。确认 while :) - qwetty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接