@@ -35,12 +35,15 @@ async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.
3535 from the current process' stdin and writing to stdout.
3636 """
3737 # Re-wrap the `fd` with `closefd=False` to force UTF-8 (Windows encoding is
38- # platform-dependant) without taking ownership of process stdio.
38+ # platform-dependent) without taking ownership of process stdio.
39+ stdin_opened = stdout_opened = False
3940 if not stdin :
4041 stdin = anyio .wrap_file (TextIOWrapper (open (sys .stdin .fileno (), "rb" , closefd = False ), encoding = "utf-8" ))
42+ stdin_opened = True
4143 if not stdout :
4244 stdout = anyio .wrap_file (TextIOWrapper (open (sys .stdout .fileno (), "wb" , closefd = False ), encoding = "utf-8" ))
43-
45+ stdout_opened = True
46+
4447 read_stream : MemoryObjectReceiveStream [SessionMessage | Exception ]
4548 read_stream_writer : MemoryObjectSendStream [SessionMessage | Exception ]
4649
@@ -75,7 +78,13 @@ async def stdout_writer():
7578 except anyio .ClosedResourceError : # pragma: no cover
7679 await anyio .lowlevel .checkpoint ()
7780
78- async with anyio .create_task_group () as tg :
79- tg .start_soon (stdin_reader )
80- tg .start_soon (stdout_writer )
81- yield read_stream , write_stream
81+ try :
82+ async with anyio .create_task_group () as tg :
83+ tg .start_soon (stdin_reader )
84+ tg .start_soon (stdout_writer )
85+ yield read_stream , write_stream
86+ finally :
87+ if stdin_opened :
88+ await stdin .aclose ()
89+ if stdout_opened :
90+ await stdout .aclose ()
0 commit comments