Skip to content

Python tool for converting files and office documents to Markdown.

fix: handle None sys.stdout.encoding in CLI output (#1656)

Octopus53f38ea102c1
diff --git a/packages/markitdown/src/markitdown/__main__.py b/packages/markitdown/src/markitdown/__main__.py
index 51b775ff..170308cf 100644
--- a/packages/markitdown/src/markitdown/__main__.py
+++ b/packages/markitdown/src/markitdown/__main__.py
@@ -269,12 +269,10 @@ def _handle_output(args, result: DocumentConverterResult):
with open(args.output, "w", encoding="utf-8") as f:
f.write(result.markdown)
else:
- # Handle stdout encoding errors more gracefully
- print(
- result.markdown.encode(sys.stdout.encoding, errors="replace").decode(
- sys.stdout.encoding
- )
- )
+ # Handle stdout encoding errors more gracefully, with fallback for
+ # cases where sys.stdout.encoding is None (e.g. redirected streams).
+ encoding = sys.stdout.encoding or "utf-8"
+ print(result.markdown.encode(encoding, errors="replace").decode(encoding))
def _exit_with_error(message: str):