Support ANSI color and style codes on Windows by wrapping a stream with colorama.
(stream: t.TextIO, color: bool | None = None)
| 524 | _ansi_stream_wrappers: cabc.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary() |
| 525 | |
| 526 | def auto_wrap_for_ansi(stream: t.TextIO, color: bool | None = None) -> t.TextIO: |
| 527 | class="st">"""Support ANSI color and style codes on Windows by wrapping a |
| 528 | stream with colorama. |
| 529 | class="st">""" |
| 530 | try: |
| 531 | cached = _ansi_stream_wrappers.get(stream) |
| 532 | except Exception: |
| 533 | cached = None |
| 534 | |
| 535 | if cached is not None: |
| 536 | return cached |
| 537 | |
| 538 | import colorama |
| 539 | |
| 540 | strip = should_strip_ansi(stream, color) |
| 541 | ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip) |
| 542 | rv = t.cast(t.TextIO, ansi_wrapper.stream) |
| 543 | _write = rv.write |
| 544 | |
| 545 | def _safe_write(s: str) -> int: |
| 546 | try: |
| 547 | return _write(s) |
| 548 | except BaseException: |
| 549 | ansi_wrapper.reset_all() |
| 550 | raise |
| 551 | |
| 552 | rv.write = _safe_write class="cm"># type: ignore[method-assign] |
| 553 | |
| 554 | try: |
| 555 | _ansi_stream_wrappers[stream] = rv |
| 556 | except Exception: |
| 557 | pass |
| 558 | |
| 559 | return rv |
| 560 | |
| 561 | else: |
| 562 |
no test coverage detected