Skip to content

Write history files and read pyscripts as UTF-8 - #1836

Open
Alpenj wants to merge 1 commit into
python-cmd2:mainfrom
Alpenj:fix-history-pyscript-utf8
Open

Alpenj wants to merge 1 commit into
python-cmd2:mainfrom
Alpenj:fix-history-pyscript-utf8

Conversation

@Alpenj

@Alpenj Alpenj commented Nov 25, 2026

Copy link
Copy Markdown

On a locale whose encoding is not UTF-8 (for example cp949 on Korean Windows, or cp1252 on Western Windows before Python 3.15), three file paths in cmd2.py used the locale's encoding while the rest of cmd2 uses UTF-8:

  • history --output-file and history --edit wrote the history in the locale's encoding. run_script reads only ASCII or UTF-8 files (utils.is_text_file()), so a history with non-ASCII text could not be run again. With --edit, the edited file is passed straight to run_script, so the commands never ran.
  • run_pyscript read the script in the locale's encoding. Python source files are UTF-8 by default, so a script with non-ASCII text failed with UnicodeDecodeError or ran with garbled strings.

Reproduction (Windows 11, Korean locale, Python 3.14, locale.getpreferredencoding() = cp949)

import cmd2

class App(cmd2.Cmd):
    def do_say(self, args):
        self.poutput(args)

app = App()
app.run_editor = lambda fname: None  # keep the file as history wrote it
app.onecmd_plus_hooks("say 한글 Łukasz")
app.onecmd_plus_hooks('history -o "hist.txt"')
app.onecmd_plus_hooks('run_script "hist.txt"')
app.onecmd_plus_hooks("history -e 1")
# s.py is saved as UTF-8 and contains: print("파이썬 스크립트 ✓")
app.onecmd_plus_hooks('run_pyscript "s.py"')

Before:

한글 Łukasz
1 command saved to ...\hist.txt
'...\hist.txt' is not an ASCII or UTF-8 encoded text file
'...\Temp\tmpoiei0xr1.txt' is not an ASCII or UTF-8 encoded text file
UnicodeDecodeError: 'cp949' codec can't decode byte 0xed in position 7: illegal
multibyte sequence

hist.txt contained b'say \xc7\xd1\xb1\xdb \xa8\xa9ukasz\r\n' (cp949).

After:

한글 Łukasz
1 command saved to ...\hist.txt
한글 Łukasz
한글 Łukasz
파이썬 스크립트 ✓

hist.txt now contains b'say \xed\x95\x9c\xea\xb8\x80 \xc5\x81ukasz\r\n' (UTF-8).

Changes

  • history --output-file and history --edit open their files with encoding="utf-8".
  • run_pyscript reads the script with encoding="utf-8-sig", so a script saved with a byte order mark (as some Windows editors do) also runs. Without stripping it, compile() fails with invalid non-printable character U+FEFF.
  • Added an entry to CHANGELOG.md under 4.4.4.

Tests

The new tests make open() and os.fdopen() in cmd2.cmd2 default to cp1252 when no encoding is given, so they fail on a UTF-8 CI runner too:

  • tests/test_history.py::test_history_output_file_is_utf8: saves a non-ASCII history, checks the file is UTF-8, and runs it with run_script.
  • tests/test_history.py::test_history_edit_runs_non_ascii_commands: history -e runs a non-ASCII command.
  • tests/test_run_pyscript.py::test_run_pyscript_reads_utf8[utf-8, utf-8-sig]: runs a UTF-8 script with and without a BOM.

Results on Windows 11 (Python 3.14.3):

  • New tests: 4 failed before the change, 4 passed after.
  • Full suite (uv run pytest): 2882 passed, 210 skipped. tests/test_cmd2.py::test_run_script_with_utf8_file failed in 1 of 2 full runs both with and without this change, and passes when run alone, so it looks flaky under xdist on Windows and unrelated.
  • ruff check, ruff format --check, ty check, and prek run on the changed files pass.

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.
@codecov

codecov Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 99.75%. Comparing base (5649a26) to head (c2f91be).

Additional details and impacted files
@@           Coverage Diff           @@
##             main    #1836   +/-   ##
=======================================
  Coverage   99.75%   99.75%           
=======================================
  Files          23       23           
  Lines        6644     6644           
=======================================
  Hits         6628     6628           
  Misses         16       16           
Flag Coverage Δ
unittests 99.75% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

@tleonhardt tleonhardt left a comment •

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.

Thank you for this PR, @Alpenj, and for the detailed write-up and Korean-locale reproduction! This is a real bug on non-UTF-8 Windows locales, and the history half of the fix looks right. history -o and history -e now write the same encoding that run_script / utils.is_text_file() require. Every other text open() in cmd2/ already passes encoding="utf-8", so this closes the remaining gaps. Shadowing open in cmd2.cmd2 to force cp1252 is a nice way to make the tests meaningful on a UTF-8 CI runner.

I left one suggestion on the run_pyscript change, to honor PEP 263 coding declarations via tokenize.open(), and one small nit on the tests.

Comment thread cmd2/cmd2.py

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?


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?

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.

2 participants