diff --git a/cmd2/cmd2.py b/cmd2/cmd2.py index ee2d16eff..c72bca86c 100644 --- a/cmd2/cmd2.py +++ b/cmd2/cmd2.py @@ -2033,7 +2033,9 @@ def ppaged( """Print output using a pager. A pager is used when the terminal is interactive and may exit immediately if the output - fits on the screen. A pager is not used inside a script (Python or text) or when output is + fits on the screen. On Windows, text with non-ASCII characters is printed directly when + using ``more``, which can silently drop Unicode output. A custom pager can still be used. + A pager is not used inside a script (Python or text) or when output is redirected or piped, and in these cases, output is sent to `poutput`. If the pager program cannot be run, for example because it is not installed, the output @@ -2092,6 +2094,11 @@ def ppaged( if console.legacy_windows: # A legacy Windows console prints ANSI style sequences as text when an external pager writes them. output = su.strip_style(output) + if sys.platform.startswith("win") and pager.casefold() in {"more", "more.com"} and not output.isascii(): + # Windows more can silently drop Unicode text while returning exit code 0. + print(output, end="", file=self.stdout, flush=True) + return + # As for a pipe: the pager gets UTF-8, and on Windows the console is UTF-8 while it runs. output_bytes = output.encode("utf-8", "replace") diff --git a/tests/test_cmd2.py b/tests/test_cmd2.py index 5e39d6640..432f5a290 100644 --- a/tests/test_cmd2.py +++ b/tests/test_cmd2.py @@ -4203,11 +4203,31 @@ def test_ppaged_with_pager(outsim_app, monkeypatch, chop) -> None: assert expected_cmd == popen_mock.call_args_list[0].args[0] +@pytest.mark.skipif(sys.platform != "win32", reason="Windows more.exe behavior") +@pytest.mark.parametrize("chop", [False, True]) +def test_ppaged_preserves_unicode_with_windows_more(outsim_app, monkeypatch, chop) -> None: + """Windows more can exit successfully without printing the Unicode text.""" + monkeypatch.setattr(outsim_app, "stdin", mock.MagicMock()) + stdout = mock.MagicMock() + monkeypatch.setattr(outsim_app, "stdout", stdout) + monkeypatch.setattr(outsim_app, "pager", "more") + monkeypatch.setattr(outsim_app, "pager_chop", "more") + popen = mock.MagicMock() + monkeypatch.setattr("subprocess.Popen", popen) + + text = "\u6f22" * 100 + " END" + outsim_app.ppaged(text, chop=chop) + + popen.assert_not_called() + assert text in "".join(call.args[0] for call in stdout.write.call_args_list) + + def test_ppaged_pages_utf8_in_a_utf8_console(outsim_app, monkeypatch) -> None: """As for a pipe: the pager gets UTF-8, and on Windows the console is UTF-8 until the pager has exited. - The pager there is more, which decodes with the console's code page. + A custom pager still receives UTF-8 on Windows. """ + monkeypatch.setattr(outsim_app, "pager", "custom-pager") stdin_mock = mock.MagicMock() stdin_mock.isatty.return_value = True monkeypatch.setattr(outsim_app, "stdin", stdin_mock)