markitdown icon indicating copy to clipboard operation
markitdown copied to clipboard

fix: handle UnicodeEncodeError on Windows terminals (closes #1802)

Open unn-Known1 opened this issue 6 months ago • 1 comments

Summary

Resolves issue #1802 by handling UnicodeEncodeError that occurs on Windows when the terminal's charmap codec (cp1252) cannot encode certain Unicode characters.

Changes

Modified __main__.py to wrap print() calls in try/except blocks to provide a graceful fallback using errors='replace' when the default encoding fails.

Files Changed

  • packages/markitdown/src/markitdown/__main__.py

    • _handle_output(): Added UnicodeEncodeError handling for stdout output
    • _exit_with_error(): Added UnicodeEncodeError handling for error messages
  • packages/markitdown/tests/test_module_misc.py

    • Added test_unicode_encoding_in_cli test to verify the fix works with various Unicode characters

Test Coverage

The new test verifies Unicode handling with:

  • Chinese characters (世界, 你好)
  • Emojis (🌍)
  • Greek letters (αβγδ)

All existing tests continue to pass.

unn-Known1 avatar May 03 '26 15:05 unn-Known1

@microsoft-github-policy-service agree

unn-Known1 avatar May 05 '26 19:05 unn-Known1

Hey there! I'm still quite new to Python's cross-platform terminal handling. I noticed you chose to fix the UnicodeEncodeError by modifying the stdout stream directly. Could you clarify why that method is preferred? Keep up the good work!

kyledaviesdev avatar May 07 '26 03:05 kyledaviesdev

Hi @kyledaviesdev! Great question about the implementation approach.

Modifying the stdout stream directly was chosen for several reasons:

  1. Non-invasive: Instead of wrapping every print() call with try/except blocks throughout the codebase, wrapping the stream once at the application entry point handles all output transparently.

  2. Comprehensive coverage: Any code that writes to stdout (including third-party libraries) automatically gets Unicode error handling without modification.

  3. Clean separation: The error handling is localized to the output layer, not scattered across business logic.

  4. Fail-safe approach: Using errors="replace" ensures output continues even when specific characters cannot be encoded, rather than crashing.

An alternative would be setting PYTHONIOENCODING=utf-8 as an environment variable, but that requires user action and may not cover all scenarios (especially on Windows with certain terminal configurations).

The direct stream modification approach provides the most robust cross-platform solution. Thanks for the thoughtful review!

unn-Known1 avatar May 17 '26 19:05 unn-Known1