From 28110c48bd21a5ba80a1ed71e8217ce903dab8be Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Thu, 23 Aug 2012 09:39:53 -0400 Subject: Fixed encoding issues when writing to stdout. In Python 2.x, if you write to stdout and stdout is piped (for example: `python -m markdown foo.txt | less`), then `sys.stdout.encoding` is `None` and an error is rasied. Commit 1132f9e20cd7a5d6be809651f1034c44c32dbc0e was an attempt to fix this, and it works in Python 2.x. However, it does not work in Python 3.x, which does not exhibit this problem. In fact, that fix actually breaks things in Python 3 whether the output is piped or not. Additionaly, in Python 2.x, the fix is not needed if the output is not being piped. As we do not have a version specific issue, but an issue with `sys.stdout.encoding`, we check for that to determine which way to go. This way, the "right thing" *should* happen every time. --- markdown/__init__.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/markdown/__init__.py b/markdown/__init__.py index 58993dd..d90d6c0 100644 --- a/markdown/__init__.py +++ b/markdown/__init__.py @@ -379,8 +379,15 @@ class Markdown: output_file.write(html) # Don't close here. User may want to write more. else: - stdout = codecs.getwriter(encoding)(sys.stdout, errors="xmlcharrefreplace") - stdout.write(html) + if sys.stdout.encoding: + # If we are in Python 3 or if we are not piping output: + sys.stdout.write(html) + else: + # In python 2.x if you pipe output on command line, + # sys.stdout.encoding is None. So lets set it: + writer = codecs.getwriter(encoding) + stdout = writer(sys.stdout, errors="xmlcharrefreplace") + stdout.write(html) return self -- cgit v1.2.3