将asyncio StreamReader中的字节泵送到文件描述符中

时间:2016-08-15 06:36:20

标签: python python-asyncio aiohttp

我有一个Python函数(用C ++实现),它从文件描述符中读取(包含在C ++端的FILE*中),我需要从asyncio.StreamReader提供函数。具体来说,阅读器是HTTP响应的内容:aiohttp.ClientResponse.content

我以为我可能open a pipe,将读取结束传递给C ++函数,将connect the write-end传递给asyncio的事件循环。但是,如何通过适当的流量控制和尽可能少的复制将数据从流读取器移动到管道?

缺少部分的代码框架如下:

# obtain the StreamReader from aiohttp
content = aiohttp_client_response.content
# create a pipe
(pipe_read_fd, pipe_write_fd) = os.pipe()

# now I need a suitable protocol to manage the pipe transport
protocol = ?
(pipe_transport, __) = loop.connect_write_pipe(lambda: protocol, pipe_write_fd)

# the protocol should start reading from `content` and writing into the pipe
return pipe_read_fd

2 个答案:

答案 0 :(得分:2)

来自subprocess_attach_write_pipe asyncio示例:

rfd, wfd = os.pipe()
pipe = open(wfd, 'wb', 0)
transport, _ = await loop.connect_write_pipe(asyncio.Protocol, pipe)
transport.write(b'data')

编辑 - 对于写入流控制,请参阅以下方法:

这是一个可能的FlowControl实施,受StreamWriter.drain的启发:

class FlowControl(asyncio.streams.FlowControlMixin):
    async def drain(self):
        await self._drain_helper()

用法:

transport, protocol = await loop.connect_write_pipe(FlowControl, pipe)
transport.write(b'data')
await protocol.drain()

答案 1 :(得分:0)

我使用ThreadPoolExecutor并阻止对os.write的调用解决了这个问题:

(read_fd, write_fd) = os.pipe()
task_1 = loop.create_task(pump_bytes_into_fd(write_fd))
task_2 = loop.run_in_executor(executor_1, parse_bytes_from_fd(read_fd))

async def pump_bytes_into_fd(write_fd):
    while True:
        chunk = await stream.read(CHUNK_SIZE)
        if chunk is None: break
        # process the chunk
        await loop.run_in_executor(executor_2, os.write, write_fd, chunk)

至关重要的是,使用两个不同的执行程序来阻止读取和写入以避免死锁。