@@ -93,6 +93,12 @@ def _open_stdout_diversion() -> int:
9393
9494def _restore_fd (fd : int , private_fd : int ) -> bool :
9595 """Point fd back at the wire; the Windows handle rebind never affects the outcome."""
96+ if fd == 1 :
97+ with suppress (Exception ):
98+ sys .stdout .flush ()
99+ if hasattr (sys .stdout , "reconfigure" ):
100+ with suppress (Exception ):
101+ sys .stdout .reconfigure (line_buffering = True )
96102 try :
97103 os .dup2 (private_fd , fd )
98104 except OSError :
@@ -123,6 +129,17 @@ def _claim_fd(
123129 _claims [fd ] = claim
124130
125131 def release () -> None :
132+ if fd == 1 :
133+ with suppress (Exception ):
134+ sys .stdout .flush ()
135+ with suppress (Exception ):
136+ stream .flush ()
137+ if hasattr (sys .stdout , "reconfigure" ):
138+ with suppress (Exception ):
139+ sys .stdout .reconfigure (line_buffering = True )
140+ if hasattr (stream , "reconfigure" ):
141+ with suppress (Exception ):
142+ stream .reconfigure (line_buffering = True )
126143 if claim .private_fd is None or _restore_fd (fd , claim .private_fd ):
127144 with _claims_lock :
128145 del _claims [fd ]
@@ -138,6 +155,11 @@ def release() -> None:
138155 except OSError :
139156 return stream .buffer , release
140157 try :
158+ if fd == 1 :
159+ with suppress (Exception ):
160+ sys .stdout .flush ()
161+ with suppress (Exception ):
162+ stream .flush ()
141163 os .dup2 (diversion_fd , fd )
142164 except OSError :
143165 # The divert did not land; ensure fd carries the wire (a Windows dup2 can
@@ -176,7 +198,7 @@ async def stdio_server(stdin: anyio.AsyncFile[str] | None = None, stdout: anyio.
176198 stdin = anyio .wrap_file (_UnownedTextWrapper (stdin_buffer , encoding = "utf-8" , errors = "replace" ))
177199 if not stdout :
178200 stdout_buffer , restore_stdout = _claim_fd (1 , sys .stdout , "wb" , _open_stdout_diversion )
179- stdout = anyio .wrap_file (_UnownedTextWrapper (stdout_buffer , encoding = "utf-8" ))
201+ stdout = anyio .wrap_file (_UnownedTextWrapper (stdout_buffer , encoding = "utf-8" , line_buffering = True ))
180202
181203 read_stream_writer , read_stream = create_context_streams [SessionMessage | Exception ](0 )
182204 write_stream , write_stream_reader = create_context_streams [SessionMessage ](0 )
0 commit comments