Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@
- On Windows, shell command completion now recognizes paths typed with forward slashes, such as
`./my` and `C:/tools/my`. Path completion preserves the typed separators so the first Tab
extends the shared prefix when several names match.
- `history --output-file` and `history --edit` now write UTF-8 files, so `run_script` can run
them again. On a locale whose encoding is not UTF-8, such as Korean or Japanese Windows, a
history with non-ASCII text was written in the locale's encoding, which `run_script` rejects
as not being an ASCII or UTF-8 encoded text file. `run_pyscript` now reads scripts as UTF-8,
the default encoding of Python source files, with or without a byte order mark, instead of in
the locale's encoding.

## 4.4.3 (2026-11-16)

Expand Down
6 changes: 3 additions & 3 deletions cmd2/cmd2.py
Original file line number Diff line number Diff line change
Expand Up @@ -5315,7 +5315,7 @@ def py_quit() -> None:
expanded_filename = os.path.expanduser(pyscript)

try:
with open(expanded_filename) as f:
with open(expanded_filename, encoding="utf-8-sig") as f:

@tleonhardt tleonhardt Nov 25, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Python reads a source file as UTF-8 by default, but it also honors a BOM and a PEP 263 # -*- coding: ... -*- line. Hard-coding utf-8-sig covers the first two cases but ignores the coding line. So a script like this:

# -*- coding: latin-1 -*-
print("café")   # saved as latin-1

now fails with an unhandled UnicodeDecodeError. That error isn't an OSError, so the user never sees the Error reading script file ... message and gets a generic exception instead. On a cp1252 locale, that script used to run.

tokenize.open() reads a file the way Python does: BOM first, then the coding line, otherwise UTF-8. It also strips the BOM, so it can replace the current call directly:

import tokenize
...
try:
    with tokenize.open(expanded_filename) as f:
        py_code_to_run = f.read()
except (OSError, SyntaxError, UnicodeDecodeError) as ex:
    self.perror(f"Error reading script file '{expanded_filename}': {ex}")
    return None

tokenize.detect_encoding() raises SyntaxError when the coding line names an unknown encoding, which is why it's in the except. I made this change locally: both test_run_pyscript_reads_utf8 cases still pass, and the latin-1 script above prints café. Could you also add a test for a script with a coding line, and one for a script that can't be decoded and so goes through the perror path?

py_code_to_run = f.read()
except OSError as ex:
self.perror(f"Error reading script file '{expanded_filename}': {ex}")
Expand Down Expand Up @@ -5628,7 +5628,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
if args.edit:
fd, fname = tempfile.mkstemp(suffix=".txt", text=True)
fobj: TextIO
with os.fdopen(fd, "w") as fobj:
with os.fdopen(fd, "w", encoding="utf-8") as fobj:
for command in history.values():
if command.statement.multiline_command:
fobj.write(f"{command.expanded}\n")
Expand All @@ -5644,7 +5644,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
elif args.output_file:
full_path = os.path.abspath(os.path.expanduser(args.output_file))
try:
with open(full_path, "w") as fobj:
with open(full_path, "w", encoding="utf-8") as fobj:
for item in history.values():
if item.statement.multiline_command:
fobj.write(f"{item.expanded}\n")
Expand Down
53 changes: 53 additions & 0 deletions tests/test_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -1473,6 +1473,59 @@ def test_history_edit(monkeypatch) -> None:
run_script_mock.assert_called_once()


@pytest.fixture
def non_utf8_locale(monkeypatch):
"""Make cmd2's open() and os.fdopen() default to cp1252, as they do on a non-UTF-8 Windows locale."""
real_open = open
real_fdopen = os.fdopen

def open_cp1252(file, mode="r", *args, **kwargs):
if "b" not in mode and not args:
kwargs.setdefault("encoding", "cp1252")
return real_open(file, mode, *args, **kwargs)

def fdopen_cp1252(fd, mode="r", *args, **kwargs):
if "b" not in mode and not args:
kwargs.setdefault("encoding", "cp1252")
return real_fdopen(fd, mode, *args, **kwargs)

monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False)
monkeypatch.setattr(cmd2.cmd2.os, "fdopen", fdopen_cp1252)


class SayApp(cmd2.Cmd):
def do_say(self, args) -> None:
self.poutput(args)


def test_history_output_file_is_utf8(non_utf8_locale, tmp_path) -> None:
app = SayApp()
run_cmd(app, "say Łukasz ✨")
fname = tmp_path / "history.txt"

run_cmd(app, f'history -o "{fname}"')

assert app.last_result is True
assert fname.read_bytes().decode("utf-8").splitlines() == ["say Łukasz ✨"]

# run_script reads only ASCII or UTF-8 files, so the saved history can be run again
out, err = run_cmd(app, f'run_script "{fname}"')
assert err == []
assert out == ["Łukasz ✨"]


def test_history_edit_runs_non_ascii_commands(non_utf8_locale, monkeypatch) -> None:
app = SayApp()
# Leave the file as history wrote it
monkeypatch.setattr("cmd2.Cmd.run_editor", lambda _self, _fname: None)
run_cmd(app, "say Łukasz ✨")

out, err = run_cmd(app, "history -e 1")

assert err == []
assert out == ["Łukasz ✨"]


def test_history_run_all_commands(base_app) -> None:
# make sure we refuse to run all commands as a default
run_cmd(base_app, "shortcuts")
Expand Down
23 changes: 23 additions & 0 deletions tests/test_run_pyscript.py
Original file line number Diff line number Diff line change
Expand Up @@ -262,3 +262,26 @@ def test_run_pyscript_print_redirection(base_app, request, tmp_path, capsys) ->
# Verify the remaining output when to the correct stream
assert "this goes to sys.stdout" in out
assert "this goes to sys.stderr" in err


@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
def test_run_pyscript_reads_utf8(base_app, tmp_path, monkeypatch, encoding) -> None:
import cmd2.cmd2

real_open = open

def open_cp1252(file, mode="r", *args, **kwargs):

@tleonhardt tleonhardt Nov 25, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this open_cp1252 duplicates the non_utf8_locale fixture in tests/test_history.py. Could you move that fixture to tests/conftest.py and use it in both test files?

# Without an explicit encoding, open() uses cp1252, as it does on a non-UTF-8 Windows locale
if "b" not in mode and not args:
kwargs.setdefault("encoding", "cp1252")
return real_open(file, mode, *args, **kwargs)

monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False)
python_script = tmp_path / "script.py"
python_script.write_text('print("Łukasz ✨")\n', encoding=encoding)

out, err = run_cmd(base_app, f'run_pyscript "{python_script}"')

assert err == []
assert out == ["Łukasz ✨"]
assert base_app.last_result is True
Loading