将 asyncio 与阻塞代码一起使用

mud*_*ish 5 python iterator python-asyncio

首先,我查看了thisthisthis,虽然第一个有一些有用的信息,但它与这里无关,因为我正在尝试迭代值。

这是我想要做的事情的一个例子:

class BlockingIter:
    def __iter__(self):
        while True:
            yield input()

async def coroutine():
    my_iter = BlockingIter()
    #Magic thing here
    async for i in my_iter:
        await do_stuff_with(i)
Run Code Online (Sandbox Code Playgroud)

我该怎么办呢?

(注意,BlockingIter实际上是我正在使用的库(chatexchange),因此可能还有其他一些复杂情况。)

Jug*_*aut 4

正如 @vaultah 所说以及文档中所解释的那样,awaiting( executor)await loop.run_in_executor(None, next, iter_messages)可能就是您想要的。