diff --git a/markdown_it/cli/parse.py b/markdown_it/cli/parse.py index 9c1f2fb3..a8aeb0cc 100644 --- a/markdown_it/cli/parse.py +++ b/markdown_it/cli/parse.py @@ -8,7 +8,10 @@ import argparse from collections.abc import Iterable, Sequence +import io +import os import sys +from typing import TextIO from markdown_it import __version__ from markdown_it.main import MarkdownIt @@ -27,14 +30,36 @@ def main(args: Sequence[str] | None = None) -> int: if namespace.enable_tables: md.enable("table") if namespace.filenames: + _use_utf8(sys.stdout) convert(namespace.filenames, md) elif namespace.stdin: + # Read standard input like a file: UTF-8, ignoring undecodable bytes. + _use_utf8(sys.stdin, errors="ignore") + _use_utf8(sys.stdout) convert_stdin(md) else: interactive(md) return 0 +def _use_utf8(stream: TextIO, errors: str | None = None) -> None: + """Use UTF-8 for a redirected or piped standard stream. + + Files are read 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`` misread UTF-8 input. + An encoding set with PYTHONIOENCODING is kept, and a terminal is left as is. + """ + if ( + os.environ.get("PYTHONIOENCODING") + or not isinstance(stream, io.TextIOWrapper) + or stream.isatty() + ): + return + stream.reconfigure(encoding="utf-8", errors=errors or stream.errors) + + def convert(filenames: Iterable[str], md: MarkdownIt | None = None) -> None: for filename in filenames: convert_file(filename, md) diff --git a/tests/test_cli.py b/tests/test_cli.py index 450c862f..45175859 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -104,6 +104,58 @@ def test_stdin(): assert string_io.getvalue() == "
abc
\n" + + +def test_redirected_stdout_keeps_pythonioencoding(tmp_path, monkeypatch): + monkeypatch.setenv("PYTHONIOENCODING", "utf-16") + path = tmp_path / "test.md" + path.write_text("# a", encoding="utf8") + stdout = _redirected("utf-16") + monkeypatch.setattr(sys, "stdout", stdout) + assert parse.main([str(path)]) == 0 + assert _written(stdout).decode("utf-16") == "