A context manager that sets up the isolation for invoking of a command line tool. This sets up ` ` with the given input data and `os.environ` with the overrides from the given dictionary.
(
self,
input: str | bytes | None = None,
env: Mapping[str, str | None] | None = None,
color: bool = False,
)
| 157 | |
| 158 | @contextlib.contextmanager |
| 159 | def isolation( |
| 160 | self, |
| 161 | input: str | bytes | None = None, |
| 162 | env: Mapping[str, str | None] | None = None, |
| 163 | color: bool = False, |
| 164 | ) -> Iterator[tuple[io.BytesIO, io.BytesIO, io.BytesIO]]: |
| 165 | """A context manager that sets up the isolation for invoking of a |
| 166 | command line tool. This sets up `<stdin>` with the given input data |
| 167 | and `os.environ` with the overrides from the given dictionary. |
| 168 | """ |
| 169 | bytes_input = make_input_stream(input, self.charset) |
| 170 | |
| 171 | old_stdin = sys.stdin |
| 172 | old_stdout = sys.stdout |
| 173 | old_stderr = sys.stderr |
| 174 | old_forced_width = formatting.FORCED_WIDTH |
| 175 | formatting.FORCED_WIDTH = 80 |
| 176 | |
| 177 | env = self.make_env(env) |
| 178 | |
| 179 | stream_mixer = StreamMixer() |
| 180 | |
| 181 | sys.stdin = text_input = _NamedTextIOWrapper( |
| 182 | bytes_input, encoding=self.charset, name="<stdin>", mode="r" |
| 183 | ) |
| 184 | |
| 185 | sys.stdout = _NamedTextIOWrapper( |
| 186 | stream_mixer.stdout, encoding=self.charset, name="<stdout>", mode="w" |
| 187 | ) |
| 188 | |
| 189 | sys.stderr = _NamedTextIOWrapper( |
| 190 | stream_mixer.stderr, |
| 191 | encoding=self.charset, |
| 192 | name="<stderr>", |
| 193 | mode="w", |
| 194 | errors="backslashreplace", |
| 195 | ) |
| 196 | |
| 197 | def visible_input(prompt: str | None = None) -> str: |
| 198 | sys.stdout.write(prompt or "") |
| 199 | try: |
| 200 | val = next(text_input).rstrip("\r\n") |
| 201 | except StopIteration as e: # pragma: no cover |
| 202 | raise EOFError() from e |
| 203 | sys.stdout.write(f"{val}\n") |
| 204 | sys.stdout.flush() |
| 205 | return val |
| 206 | |
| 207 | def hidden_input(prompt: str | None = None) -> str: |
| 208 | sys.stdout.write(f"{prompt or ''}\n") |
| 209 | sys.stdout.flush() |
| 210 | try: |
| 211 | return next(text_input).rstrip("\r\n") |
| 212 | except StopIteration as e: # pragma: no cover |
| 213 | raise EOFError() from e |
| 214 | |
| 215 | def _getchar(echo: bool) -> str: |
| 216 | char = sys.stdin.read(1) |
no test coverage detected