@@ -449,12 +449,33 @@ def _deliver(self, value: str) -> None:
449449 if value :
450450 # A replacement flush() may log. Call it only during
451451 # delivery, outside both the buffer and transition locks.
452- self .flush ()
452+ try :
453+ self .flush ()
454+ except BaseException :
455+ # The text was taken already. Put it back in front of
456+ # anything written since, so a flush() that fails once
457+ # (a handler that is not ready yet) costs no output.
458+ self ._restore (value )
459+ raise
453460 if value and not self .target .closed :
454461 self .target .write (value )
455462 # when explicitly flushing, always flush the target as well
456463 self .flush_target ()
457464
465+ def _restore (self , value : str ) -> None :
466+ """Put text taken by `_take()` back, ahead of later writes."""
467+ with (
468+ self ._buffer_box .lock
469+ if self ._native_buffer ()
470+ else contextlib .nullcontext ()
471+ ):
472+ rest : str = self .buffer .getvalue ()
473+ self .buffer .seek (0 )
474+ self .buffer .truncate (0 )
475+ self .buffer .write (value + rest )
476+ if '\n ' in value :
477+ self .needs_clear = True
478+
458479 def flush_target (self ) -> None : # pragma: no cover
459480 """Flush `target` itself, if it's open and flushable."""
460481 if not self .target .closed and getattr (self .target , 'flush' , None ):
@@ -681,6 +702,11 @@ def stop_capturing(self, bar: _ProgressListener | None = None) -> None:
681702 """
682703 pending : list [_Pending ] = []
683704 failure : BaseException | None = None
705+ # The default hook drains and delivers through `flush()`, as
706+ # 4.6.0 did, so the original stream is flushed once. Only a
707+ # replaced hook, which may not call `super()`, needs this stop
708+ # to deliver its own text before the hook runs.
709+ deliver : bool = not self ._default_capture_hook ()
684710 with self .lock :
685711 if bar : # pragma: no branch
686712 with self .listeners_lock , contextlib .suppress (KeyError ):
@@ -690,16 +716,24 @@ def stop_capturing(self, bar: _ProgressListener | None = None) -> None:
690716 # the next start_capturing() a no-op
691717 self .capturing = max (self .capturing - 1 , 0 )
692718 try :
693- pending = self ._apply_capturing ()
719+ if deliver :
720+ pending = self ._apply_capturing ()
721+ else :
722+ self ._propagate_capturing ()
694723 except BaseException as exception : # noqa: BLE001
695724 failure = exception
696- if failure is None :
725+ if failure is None and pending :
697726 try :
698727 self ._deliver (pending )
699728 except BaseException as exception : # noqa: BLE001
700729 failure = exception
701730 self ._notify_capturing (failure )
702731
732+ def _default_capture_hook (self ) -> bool :
733+ """Return whether `update_capturing` is the one defined here."""
734+ hook : object = getattr (self .update_capturing , '__func__' , None )
735+ return hook is StreamWrapper .update_capturing
736+
703737 def _notify_capturing (self , failure : BaseException | None ) -> None :
704738 """Notify the public hook without replacing an earlier failure."""
705739 if failure is None :
@@ -720,22 +754,28 @@ def update_capturing(self) -> None: # pragma: no cover
720754 until something else happens to trigger a flush.
721755
722756 Start and stop invoke overrides after the state propagation
723- attempt. Stop also attempts delivery before invoking the hook,
724- even if that attempt fails. Calling `super()` reconciles the
725- current state again and can flush an already empty target .
757+ attempt. A stop with a replaced hook also delivers its own text
758+ before invoking it, even if that delivery fails. Calling
759+ `super()` reconciles the current state again and flushes .
726760 Concurrent transitions can change the state before the hook
727761 runs, so it can observe a later transition's count and flags.
728762 """
729763 with self .lock :
730- pending : list [_Pending ] = self ._apply_capturing ()
731- self ._deliver (pending )
764+ self ._propagate_capturing ()
732765 if self .capturing <= 0 :
733766 # 4.6.0 flushed through the public method here, so a
734767 # subclass that overrides `flush()` sees the last bar stop
735- # capturing. The text itself went out above, this drains
736- # whatever a listener wrote in between.
768+ # capturing, and the original stream is flushed once.
737769 self .flush ()
738770
771+ def _propagate_capturing (self ) -> None :
772+ """Push the capture flag onto the installed wrappers, under `lock`."""
773+ if isinstance (self .stdout , WrappingIO ):
774+ self .stdout .capturing = self .capturing > 0
775+
776+ if isinstance (self .stderr , WrappingIO ):
777+ self .stderr .capturing = self .capturing > 0
778+
739779 def _apply_capturing (self ) -> list [_Pending ]:
740780 """Push the capture state onto the wrappers, under `lock`.
741781
@@ -748,12 +788,7 @@ def _apply_capturing(self) -> list[_Pending]:
748788 same text twice, and an unwrap cannot swap the wrapper out
749789 between the type check and the drain.
750790 """
751- if isinstance (self .stdout , WrappingIO ):
752- self .stdout .capturing = self .capturing > 0
753-
754- if isinstance (self .stderr , WrappingIO ):
755- self .stderr .capturing = self .capturing > 0
756-
791+ self ._propagate_capturing ()
757792 if self .capturing > 0 :
758793 return []
759794 return self ._take ()
0 commit comments