【问题标题】:python asyncio run_forever or while Truepython asyncio run_forever 或 while True
【发布时间】:2015-09-24 12:16:35
【问题描述】:

我应该在我的代码中替换 while True(没有 asyncio)还是应该使用 asyncio 事件循环来完成相同的结果。

目前我正在研究某种连接到 zeromq 的“worker”,接收一些数据,然后对外部工具(服务器)执行一些请求(http)。一切都写在 normal 阻塞 IO 中。使用 asyncio 事件循环摆脱while True: ... 有意义吗?

将来它可能会完全用 asyncio 重写,但现在我害怕从 asyncio 开始。

我是 asyncio 的新手,并不是这个库的所有部分对我来说都很清楚 :)

谢谢:)

【问题讨论】:

  • 如果你打算尝试使用asyncio,你应该使用aiozmq和其他asyncio友好的库完全重写程序。尝试将阻塞库与 asyncio 事件循环混合使用,特别是如果您只是为了删除 while True: 循环而这样做,这通常不是一个好主意。

标签: python python-asyncio


【解决方案1】:

如果您想使用不支持的库开始编写 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: 还是其他可能的异步方式?
  • @qwetty 在协程中拥有while True 非常好,只要您在协程中执行异步调用。检查examples,例如hello_coroutine
  • 谢谢。这就是我需要的。关于while的确认:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-10
  • 2022-11-23
  • 2019-02-25
  • 2018-09-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多