aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWaylan Limberg <waylan@gmail.com>2012-08-23 09:39:53 -0400
committerWaylan Limberg <waylan@gmail.com>2012-08-23 09:39:53 -0400
commit28110c48bd21a5ba80a1ed71e8217ce903dab8be (patch)
tree680da21abd38e7b6de11faba6f9b21ed83669a04
parent2789026a0114dba2e8d60be71b4d7c8cc6eb61ed (diff)
downloadmarkdown-28110c48bd21a5ba80a1ed71e8217ce903dab8be.tar.gz
markdown-28110c48bd21a5ba80a1ed71e8217ce903dab8be.tar.bz2
markdown-28110c48bd21a5ba80a1ed71e8217ce903dab8be.zip
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.
-rw-r--r--markdown/__init__.py11
1 files 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