aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWaylan Limberg <waylan@gmail.com>2012-11-07 20:14:05 -0500
committerWaylan Limberg <waylan@gmail.com>2012-11-07 20:14:05 -0500
commitf2d5aa83bbbd7cb260ea78dd8dfb4e2d4db4f7f7 (patch)
tree2a983c6ce6734659ea46ebf6260c6ea6afd5e20a
parent54a00d12c03ab3c05ffb57f5797b96b31b6d894f (diff)
downloadmarkdown-f2d5aa83bbbd7cb260ea78dd8dfb4e2d4db4f7f7.tar.gz
markdown-f2d5aa83bbbd7cb260ea78dd8dfb4e2d4db4f7f7.tar.bz2
markdown-f2d5aa83bbbd7cb260ea78dd8dfb4e2d4db4f7f7.zip
Fixed #158. Now properly encoding output to stdout.
This is another try at this problem. The trick is geting code that works with both Python 2 and Python 3. I think this does it. The only improvment I can see now is to catch any errors and customize the error message to sugg that the user set the environment variable PYTHONIOENCODING to the desired encoding before calling the commandline script.
-rw-r--r--markdown/__init__.py15
1 files changed, 7 insertions, 8 deletions
diff --git a/markdown/__init__.py b/markdown/__init__.py
index cda6b76..1b71295 100644
--- a/markdown/__init__.py
+++ b/markdown/__init__.py
@@ -379,15 +379,14 @@ class Markdown:
output_file.write(html)
# Don't close here. User may want to write more.
else:
- if sys.stdout.encoding:
- # If we are in Python 3 or if we are not piping output:
+ # Encode manually and write bytes to stdout.
+ html = html.encode(encoding, errors="xmlcharrefreplace")
+ try:
+ # Write bytes directly to buffer (Python 3).
+ sys.stdout.buffer.write(html)
+ except AttributeError:
+ # Probably Python 2, which works with bytes by default.
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