[英]How to create asyncio stream reader/writer for stdin/stdout?
我需要編寫兩個程序,它們將作為父進程及其子進程運行。 父進程生成子進程,然后通過連接到子進程stdin和stdout的一對管道進行通信。 通信是點對點的,這就是我需要asyncio的原因。 一個簡單的讀/回放循環是行不通的。
我寫過父母。 沒問題,因為asyncio
提供了我在create_subprocess_exec()
所需的一切。
但是我不知道如何在孩子中創建類似的流讀取器/寫入器。 我沒想到會有任何問題。 因為已經創建了管道,並且在子進程啟動時可以使用文件描述符0和1。 沒有連接是打開的,不需要生成任何進程。
這是我不努力的嘗試:
import asyncio
import sys
_DEFAULT_LIMIT = 64 * 1024
async def connect_stdin_stdout(limit=_DEFAULT_LIMIT, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
r_transport, _ = await loop.connect_read_pipe(lambda: protocol, sys.stdin)
w_transport, _ = await loop.connect_write_pipe(lambda: protocol, sys.stdout)
writer = asyncio.StreamWriter(w_transport, protocol, reader, loop)
return reader, writer
問題是我有兩個運輸工具,我應該有一個。 該函數失敗,因為它嘗試將協議的傳輸設置兩次:
await loop.connect_read_pipe(lambda: protocol, sys.stdin)
await loop.connect_write_pipe(lambda: protocol, sys.stdout)
# !!!! assert self._transport is None, 'Transport already set'
我試圖將偽協議傳遞給第一行,但這行也不正確,因為需要兩個傳輸,而不僅僅是一個:
writer = asyncio.StreamWriter(w_transport, protocol, reader, loop)
我想我需要以某種方式將兩個單向傳輸組合到一個雙向。 或者我的方法完全錯了? 你能給我一些建議嗎?
更新 :經過一些測試后,這似乎有效(但對我來說不好看):
async def connect_stdin_stdout(limit=_DEFAULT_LIMIT, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
reader = asyncio.StreamReader(limit=limit, loop=loop)
protocol = asyncio.StreamReaderProtocol(reader, loop=loop)
dummy = asyncio.Protocol()
await loop.connect_read_pipe(lambda: protocol, sys.stdin) # sets read_transport
w_transport, _ = await loop.connect_write_pipe(lambda: dummy, sys.stdout)
writer = asyncio.StreamWriter(w_transport, protocol, reader, loop)
return reader, writer
您的第一個版本失敗,因為您使用了錯誤的協議作者; StreamReaderProtocol
實現了對傳入連接和數據作出反應的鈎子,這是寫作方不會也不應該處理的事情。
loop.connect_write_pipe()
協程使用您傳入的協議工廠並返回生成的協議實例。 您確實希望在流編寫器中使用相同的協議對象,而不是用於閱讀器的協議。
接下來,您不希望將stdin
讀取器傳遞給stdout
流stdin
器! 該類假定讀者和編寫者連接到同一個文件描述符,而這種情況實際上並非如此。
在最近的過去,我構建了以下內容來處理子進程的stdio; stdio()
函數基於Nathan Hoad關於該主題的要點 ,加上Windows的后備,其中支持將stdio視為管道的限制 。
你確實希望asyncio.streams.FlowControlMixin
正確處理背壓,所以我的版本使用(未記錄的) asyncio.streams.FlowControlMixin
類作為協議; 你真的不需要更多:
import asyncio
import os
import sys
async def stdio(limit=asyncio.streams._DEFAULT_LIMIT, loop=None):
if loop is None:
loop = asyncio.get_event_loop()
if sys.platform == 'win32':
return _win32_stdio(loop)
reader = asyncio.StreamReader(limit=limit, loop=loop)
await loop.connect_read_pipe(
lambda: asyncio.StreamReaderProtocol(reader, loop=loop), sys.stdin)
writer_transport, writer_protocol = await loop.connect_write_pipe(
lambda: asyncio.streams.FlowControlMixin(loop=loop),
os.fdopen(sys.stdout.fileno(), 'wb'))
writer = asyncio.streams.StreamWriter(
writer_transport, writer_protocol, None, loop)
return reader, writer
def _win32_stdio(loop):
# no support for asyncio stdio yet on Windows, see https://bugs.python.org/issue26832
# use an executor to read from stdio and write to stdout
# note: if nothing ever drains the writer explicitly, no flushing ever takes place!
class Win32StdinReader:
def __init__(self):
self.stdin = sys.stdin.buffer
async def readline():
# a single call to sys.stdin.readline() is thread-safe
return await loop.run_in_executor(None, self.stdin.readline)
class Win32StdoutWriter:
def __init__(self):
self.buffer = []
self.stdout = sys.stdout.buffer
def write(self, data):
self.buffer.append(data)
async def drain(self):
data, self.buffer = self.buffer, []
# a single call to sys.stdout.writelines() is thread-safe
return await loop.run_in_executor(None, sys.stdout.writelines, data)
return Win32StdinReader(), Win32StdoutWriter()
雖然可能已經過時了一點,但我發現Nathaniel J. Smith在2016年的博客文章中對asyncio和curio 非常有幫助,因為它非常有助於理解asyncio,協議,傳輸和背壓等所有這些內容的相互作用和掛起。 該文章還說明了為什么為stdio
創建reader和writer對象目前是如此冗長和繁瑣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.