Skip to content

Commit

Permalink
DEV: Create ReplaceSysIoContextManager
Browse files Browse the repository at this point in the history
Extracts the action of replacing sys.std* handles into a
separate context manager, so that alternative implementations
can re-use this component with other streams, or create wrappers
that do not use this functionality.
  • Loading branch information
jayvdb committed Sep 7, 2019
1 parent 0385218 commit 20be80c
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 18 deletions.
23 changes: 5 additions & 18 deletions src/stdio_mgr/stdio_mgr.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
"""

import sys
from contextlib import suppress
from io import (
BufferedRandom,
Expand All @@ -38,7 +37,7 @@
TextIOWrapper,
)

from .types import _MultiCloseContextManager
from .types import _MultiCloseContextManager, ReplaceSysIoContextManager


class _PersistedBytesIO(BytesIO):
Expand Down Expand Up @@ -267,7 +266,7 @@ class SafeCloseTeeStdin(_SafeCloseIOBase, TeeStdin):
"""


class StdioManager(_MultiCloseContextManager):
class StdioManager(ReplaceSysIoContextManager, _MultiCloseContextManager):
r"""Substitute temporary text buffers for `stdio` in a managed context.
Context manager.
Expand Down Expand Up @@ -324,22 +323,10 @@ def __new__(cls, in_str="", close=True):

return self

def __enter__(self):
"""Enter context, replacing sys stdio objects with capturing streams."""
self._prior_streams = (sys.stdin, sys.stdout, sys.stderr)

super().__enter__()

(sys.stdin, sys.stdout, sys.stderr) = self

return self

def __exit__(self, exc_type, exc_value, traceback):
"""Exit context, closing files and restoring state of sys module."""
(sys.stdin, sys.stdout, sys.stderr) = self._prior_streams

def close(self):
"""Close files only if requested."""
if self._close:
super().__exit__(exc_type, exc_value, traceback)
return super().close()


stdio_mgr = StdioManager
20 changes: 20 additions & 0 deletions src/stdio_mgr/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,3 +157,23 @@ def __exit__(self, exc_type, exc_value, traceback):
"""Exit context, closing all members."""
self.close()
return super().__exit__(exc_type, exc_value, traceback)


class ReplaceSysIoContextManager(StdioTuple):
"""Replace sys stdio with members of the tuple."""

def __enter__(self):
"""Enter context, replacing sys stdio objects with capturing streams."""
self._prior_streams = (sys.stdin, sys.stdout, sys.stderr)

super().__enter__()

(sys.stdin, sys.stdout, sys.stderr) = self

return self

def __exit__(self, exc_type, exc_value, traceback):
"""Exit context, restoring state of sys module."""
(sys.stdin, sys.stdout, sys.stderr) = self._prior_streams

return super().__exit__(exc_type, exc_value, traceback)

0 comments on commit 20be80c

Please sign in to comment.