A Windows user runs your CLI and sends a screenshot: instead of a green "ok", the output reads ←[32mok←[0m. The escape sequences your tool emits for colour — the ANSI/VT100 control codes every Linux and macOS terminal understands — are being printed literally. Modern Windows can interpret them, but only when a console mode flag called virtual terminal processing is enabled, and whether it is depends on the host: Windows Terminal turns it on, the classic console host (conhost.exe) behind older cmd.exe and PowerShell windows often does not, and output redirected to a file never interprets anything. This guide explains the mechanism, shows when Rich, Click and colorama handle it for you, how to enable it yourself for raw escape codes, how to keep escape codes out of files and pipes, and how to test the logic on any platform. It belongs to the cross-platform terminal topic.
Prerequisites
- A CLI that emits colour, either through a library or as raw
\x1b[...msequences. - Access to a Windows machine (or a CI runner) to confirm the behaviour, since Linux and macOS terminals always interpret the codes.
Why the codes appear
On Windows 10 and later, the console host can parse VT sequences — colours, cursor movement, clearing lines — but only for a console handle whose mode includes ENABLE_VIRTUAL_TERMINAL_PROCESSING. Windows Terminal (the default terminal on Windows 11) enables it for every program; the legacy console host leaves it to the program to enable. When it is off, the escape character is shown as a glyph (often ←) followed by the rest of the sequence. Very old Windows versions cannot interpret the codes at all; there, colour must go through the Win32 console API or not happen.
The fix is to enable the flag on the console handles the program writes to, early, once — or to use a library that does.
The recipe
If you use Rich, Click or Typer
Rich detects the Windows console and either enables VT processing or falls back to the legacy Win32 API, so Rich output — and therefore Typer's help and errors — is correct without extra work. Click is more hands-off: click.echo strips styles when output is not a terminal, but current Click versions no longer depend on colorama, so on a legacy Windows console the styled text from click.style needs VT processing enabled, as below. In practice, the escape-code problem appears when code writes raw sequences with print() or sys.stdout.write(), or uses a small colour helper that assumes a POSIX terminal.
Enabling virtual terminal processing yourself
For code that writes escape codes directly, enable the console mode at startup. The standard library has no function for it, so use ctypes:
# src/mytool/winconsole.py
from __future__ import annotations
import os
import sys
ENABLE_VIRTUAL_TERMINAL_PROCESSING = 0x0004
STD_OUTPUT_HANDLE = -11
STD_ERROR_HANDLE = -12
def enable_vt_mode() -> bool:
"""Enable ANSI escape processing on Windows consoles. Returns True if VT is usable."""
if os.name != "nt":
return True # POSIX terminals always interpret VT codes
import ctypes
from ctypes import wintypes
kernel32 = ctypes.WinDLL("kernel32", use_last_error=True)
ok = True
for handle_id in (STD_OUTPUT_HANDLE, STD_ERROR_HANDLE):
handle = kernel32.GetStdHandle(handle_id)
mode = wintypes.DWORD()
if not kernel32.GetConsoleMode(handle, ctypes.byref(mode)):
ok = False # not a console (redirected) or no console
continue
if not mode.value & ENABLE_VIRTUAL_TERMINAL_PROCESSING:
if not kernel32.SetConsoleMode(handle, mode.value | ENABLE_VIRTUAL_TERMINAL_PROCESSING):
ok = False # very old Windows: VT not supported
return ok
Call it once in your entry point, before writing anything coloured. It changes only the current console's mode, and only for handles that are actually consoles; when output is redirected, GetConsoleMode fails and the function reports that VT is not usable there — which is the right answer, because a file should not receive escape codes anyway.
If you prefer a dependency to ctypes, colorama's just_fix_windows_console() does the same job (enabling VT where possible and translating codes on very old systems), and is a no-op on other platforms.
Keep escape codes out of files and pipes
Enabling VT processing solves the console; it does nothing for mytool report > report.txt, where escape codes end up in the file on every platform. The general rule from respecting NO_COLOR and FORCE_COLOR applies: only emit colour when the stream is a terminal. For text that already contains codes — output captured from a subprocess, for example — strip them before writing to a file:
# src/mytool/ansi.py
import re
_ANSI = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)")
def strip_ansi(text: str) -> str:
"""Remove CSI sequences (colours, cursor moves) and OSC sequences (titles, links)."""
return _ANSI.sub("", text)
The pattern covers CSI sequences (ESC [ … final byte), which include all colour and cursor codes, and OSC sequences (ESC ] … terminator), which terminals use for window titles and hyperlinks. Rich's Text.from_ansi(...).plain does the same if Rich is already a dependency.
Where to call it
The right place is the very start of the program — the console-script entry function — before any output and before importing modules that might print. Calling it inside a command is too late for anything printed during startup, and calling it in several places is harmless but untidy:
# src/mytool/__main__.py
from mytool.winconsole import enable_vt_mode
def main() -> None:
vt_ok = enable_vt_mode()
from mytool.cli import app # import after the console is configured
app(obj={"color": vt_ok})
Passing the result into the application lets the colour decision combine all the inputs — whether VT works, whether the stream is a terminal, NO_COLOR — in one place, as in the output policy from supporting dumb terminals and screen readers.
UX considerations
- Prefer a library over raw codes. Rich and Click already handle detection, Windows and
NO_COLOR; hand-written escape codes re-create every one of these bugs. - Fail gracefully. If
enable_vt_mode()returnsFalseon a console, switch colour off rather than printing garbage. - Mention Windows Terminal in docs. Users on the legacy console get a noticeably better experience in Windows Terminal; saying so in troubleshooting docs saves support time.
- Test on real Windows. A CI job on
windows-latestrunning the CLI and capturing output catches regressions, as in running CLI tests on Windows and macOS runners.
Testing the behaviour
The stripping function and the platform branch are testable anywhere; the Windows API path is best exercised on a Windows runner:
# tests/test_ansi.py
import os
import sys
import pytest
from mytool.ansi import strip_ansi
from mytool.winconsole import enable_vt_mode
def test_strips_colours_cursor_moves_and_links():
text = ("\x1b[32mok\x1b[0m \x1b[2K\x1b[1Gdone "
"\x1b]8;;https://example.com\x1b\\link\x1b]8;;\x1b\\")
assert strip_ansi(text) == "ok done link"
def test_plain_text_is_untouched():
assert strip_ansi("50% [done] ~/a.txt") == "50% [done] ~/a.txt"
@pytest.mark.skipif(os.name == "nt", reason="POSIX behaviour")
def test_posix_always_supports_vt():
assert enable_vt_mode() is True
@pytest.mark.skipif(os.name != "nt", reason="needs a Windows console")
def test_windows_redirected_output_reports_no_console():
# Under pytest, stdout is captured (not a console), so VT is reported unusable.
assert enable_vt_mode() is False or sys.stdout.isatty()
The hyperlink case in the first test matters: OSC 8 links are increasingly common in CLI output, and a stripping regex that only knows colour codes leaves fragments like ]8;;https://… in files.
Conclusion
Literal ←[32m sequences on Windows mean virtual terminal processing is off for that console. Rich and Typer handle it for you; plain Click and code that writes raw escape codes should call a small enable_vt_mode() (or colorama's just_fix_windows_console()) once at startup and turn colour off if it fails. Independently of the console, never send escape codes to files or pipes — check for a terminal, and strip CSI and OSC sequences from captured text before writing it. Test the stripping everywhere and the console path on a Windows runner.
Frequently asked questions
Why does the same program show colours in Windows Terminal but not in an old cmd window?
Windows Terminal enables VT processing for every program; the legacy console host requires each program to enable it. Programs that call SetConsoleMode (or use a library that does) work in both.
Does os.system("") really fix colours?
It is a well-known side effect: starting a subprocess through cmd enables VT processing on the shared console in many setups. It is undocumented behaviour and spawns a shell for nothing — use the explicit API call instead.
Are emoji and box-drawing characters the same problem?
No — those are an encoding problem, not an escape-code one. They are covered in fixing Unicode and encoding errors on Windows.
Should I enable VT processing in a library?
No. Changing console modes is a decision for the application's entry point. Libraries should emit plain text or use the host application's console object.
What about Git Bash and other MSYS terminals on Windows?
Mintty, the terminal behind Git Bash, interprets VT sequences itself, but programs see a pipe rather than a Windows console, so isatty() may report False and colour switches off. FORCE_COLOR=1 is the escape hatch users in those terminals can set; honouring it is part of the conventions in the NO_COLOR guide.