Skip to content

Commit c2f91be

Browse files
committed
Write history files and read pyscripts as UTF-8
history --output-file and history --edit wrote their files in the locale's encoding, but run_script reads only ASCII or UTF-8 files. On a locale whose encoding is not UTF-8, such as cp949 on Korean Windows, a history with non-ASCII text could not be run again: run_script said the file "is not an ASCII or UTF-8 encoded text file". Both now write UTF-8. run_pyscript read the script in the locale's encoding, so a UTF-8 script with non-ASCII text failed with UnicodeDecodeError or ran with garbled strings. It now reads the script as UTF-8, the default encoding of Python source, and accepts a byte order mark.
1 parent 5649a26 commit c2f91be

4 files changed

Lines changed: 85 additions & 3 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,12 @@
44
- On Windows, shell command completion now recognizes paths typed with forward slashes, such as
55
`./my` and `C:/tools/my`. Path completion preserves the typed separators so the first Tab
66
extends the shared prefix when several names match.
7+
- `history --output-file` and `history --edit` now write UTF-8 files, so `run_script` can run
8+
them again. On a locale whose encoding is not UTF-8, such as Korean or Japanese Windows, a
9+
history with non-ASCII text was written in the locale's encoding, which `run_script` rejects
10+
as not being an ASCII or UTF-8 encoded text file. `run_pyscript` now reads scripts as UTF-8,
11+
the default encoding of Python source files, with or without a byte order mark, instead of in
12+
the locale's encoding.
713

814
## 4.4.3 (2026-11-16)
915

‎cmd2/cmd2.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5315,7 +5315,7 @@ def py_quit() -> None:
53155315
expanded_filename = os.path.expanduser(pyscript)
53165316

53175317
try:
5318-
with open(expanded_filename) as f:
5318+
with open(expanded_filename, encoding="utf-8-sig") as f:
53195319
py_code_to_run = f.read()
53205320
except OSError as ex:
53215321
self.perror(f"Error reading script file '{expanded_filename}': {ex}")
@@ -5628,7 +5628,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
56285628
if args.edit:
56295629
fd, fname = tempfile.mkstemp(suffix=".txt", text=True)
56305630
fobj: TextIO
5631-
with os.fdopen(fd, "w") as fobj:
5631+
with os.fdopen(fd, "w", encoding="utf-8") as fobj:
56325632
for command in history.values():
56335633
if command.statement.multiline_command:
56345634
fobj.write(f"{command.expanded}\n")
@@ -5644,7 +5644,7 @@ def do_history(self, args: argparse.Namespace) -> bool | None:
56445644
elif args.output_file:
56455645
full_path = os.path.abspath(os.path.expanduser(args.output_file))
56465646
try:
5647-
with open(full_path, "w") as fobj:
5647+
with open(full_path, "w", encoding="utf-8") as fobj:
56485648
for item in history.values():
56495649
if item.statement.multiline_command:
56505650
fobj.write(f"{item.expanded}\n")

‎tests/test_history.py‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1473,6 +1473,59 @@ def test_history_edit(monkeypatch) -> None:
14731473
run_script_mock.assert_called_once()
14741474

14751475

1476+
@pytest.fixture
1477+
def non_utf8_locale(monkeypatch):
1478+
"""Make cmd2's open() and os.fdopen() default to cp1252, as they do on a non-UTF-8 Windows locale."""
1479+
real_open = open
1480+
real_fdopen = os.fdopen
1481+
1482+
def open_cp1252(file, mode="r", *args, **kwargs):
1483+
if "b" not in mode and not args:
1484+
kwargs.setdefault("encoding", "cp1252")
1485+
return real_open(file, mode, *args, **kwargs)
1486+
1487+
def fdopen_cp1252(fd, mode="r", *args, **kwargs):
1488+
if "b" not in mode and not args:
1489+
kwargs.setdefault("encoding", "cp1252")
1490+
return real_fdopen(fd, mode, *args, **kwargs)
1491+
1492+
monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False)
1493+
monkeypatch.setattr(cmd2.cmd2.os, "fdopen", fdopen_cp1252)
1494+
1495+
1496+
class SayApp(cmd2.Cmd):
1497+
def do_say(self, args) -> None:
1498+
self.poutput(args)
1499+
1500+
1501+
def test_history_output_file_is_utf8(non_utf8_locale, tmp_path) -> None:
1502+
app = SayApp()
1503+
run_cmd(app, "say Łukasz ✨")
1504+
fname = tmp_path / "history.txt"
1505+
1506+
run_cmd(app, f'history -o "{fname}"')
1507+
1508+
assert app.last_result is True
1509+
assert fname.read_bytes().decode("utf-8").splitlines() == ["say Łukasz ✨"]
1510+
1511+
# run_script reads only ASCII or UTF-8 files, so the saved history can be run again
1512+
out, err = run_cmd(app, f'run_script "{fname}"')
1513+
assert err == []
1514+
assert out == ["Łukasz ✨"]
1515+
1516+
1517+
def test_history_edit_runs_non_ascii_commands(non_utf8_locale, monkeypatch) -> None:
1518+
app = SayApp()
1519+
# Leave the file as history wrote it
1520+
monkeypatch.setattr("cmd2.Cmd.run_editor", lambda _self, _fname: None)
1521+
run_cmd(app, "say Łukasz ✨")
1522+
1523+
out, err = run_cmd(app, "history -e 1")
1524+
1525+
assert err == []
1526+
assert out == ["Łukasz ✨"]
1527+
1528+
14761529
def test_history_run_all_commands(base_app) -> None:
14771530
# make sure we refuse to run all commands as a default
14781531
run_cmd(base_app, "shortcuts")

‎tests/test_run_pyscript.py‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -262,3 +262,26 @@ def test_run_pyscript_print_redirection(base_app, request, tmp_path, capsys) ->
262262
# Verify the remaining output when to the correct stream
263263
assert "this goes to sys.stdout" in out
264264
assert "this goes to sys.stderr" in err
265+
266+
267+
@pytest.mark.parametrize("encoding", ["utf-8", "utf-8-sig"])
268+
def test_run_pyscript_reads_utf8(base_app, tmp_path, monkeypatch, encoding) -> None:
269+
import cmd2.cmd2
270+
271+
real_open = open
272+
273+
def open_cp1252(file, mode="r", *args, **kwargs):
274+
# Without an explicit encoding, open() uses cp1252, as it does on a non-UTF-8 Windows locale
275+
if "b" not in mode and not args:
276+
kwargs.setdefault("encoding", "cp1252")
277+
return real_open(file, mode, *args, **kwargs)
278+
279+
monkeypatch.setattr(cmd2.cmd2, "open", open_cp1252, raising=False)
280+
python_script = tmp_path / "script.py"
281+
python_script.write_text('print("Łukasz ✨")\n', encoding=encoding)
282+
283+
out, err = run_cmd(base_app, f'run_pyscript "{python_script}"')
284+
285+
assert err == []
286+
assert out == ["Łukasz ✨"]
287+
assert base_app.last_result is True

0 commit comments

Comments
 (0)