Skip to content

FIX: Use UTF-8 for redirected CLI input and output - #486

Open
Zephyr4772 wants to merge 1 commit into
executablebooks:masterfrom
Zephyr4772:fix/cli-utf8-streams
Open

Zephyr4772 wants to merge 1 commit into
executablebooks:masterfrom
Zephyr4772:fix/cli-utf8-streams

Conversation

@Zephyr4772

Copy link
Copy Markdown

On Windows, markdown-it doc.md > doc.html fails with UnicodeEncodeError: 'charmap' codec can't encode characters when the Markdown contains characters outside cp1252 (e.g. Gujarati, ʤ, ✓). The CLI reads files as UTF-8, but Python writes a redirected or piped stdout in the locale encoding. --stdin has the matching problem on input: piped UTF-8 is decoded as cp1252, so the parser sees mojibake, which only round-trips back to the right bytes on output.

When converting files or stdin, main() now reconfigures a redirected stdout to UTF-8, and a redirected stdin to UTF-8 with errors="ignore", the same as convert_file reads files. An encoding set with PYTHONIOENCODING is kept, and interactive and terminal use is unchanged.

Tests use stand-ins for cp1252 streams. Three of the new tests (file to stdout, stdin, undecodable stdin bytes) fail on master, and one checks PYTHONIOENCODING is kept. On Windows (Python 3.12) the suite passes except two existing pytest-regressions fixture tests that fail without PYTHONUTF8=1 on master too. Ruff 0.17.4 and mypy 2.4.1 pass.

I used Claude Code to help write this change; I reviewed and tested it.

The CLI reads files as UTF-8, but Python uses the locale encoding (e.g.
cp1252 on Windows) for standard streams that are not a terminal. So
`markdown-it doc.md > doc.html` raised UnicodeEncodeError for characters
outside it, and `--stdin` decoded UTF-8 input as cp1252.

When converting files or stdin, redirected stdout now writes UTF-8 and
redirected stdin is read as UTF-8, ignoring undecodable bytes like files.
PYTHONIOENCODING is kept and a terminal is left as is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant