aboutsummaryrefslogtreecommitdiffstats
path: root/markdown/__init__.py
diff options
context:
space:
mode:
authorWaylan Limberg <waylan@gmail.com>2011-12-28 15:59:47 -0500
committerWaylan Limberg <waylan@gmail.com>2011-12-28 15:59:47 -0500
commit566b4ed42c6df79cddedf3cd436fb8d31af22600 (patch)
tree4fb196f04072f4253407e705778e315ee3100f67 /markdown/__init__.py
parent07177cedb798d97213040f3086c4ba0d582dfbd4 (diff)
downloadmarkdown-566b4ed42c6df79cddedf3cd436fb8d31af22600.tar.gz
markdown-566b4ed42c6df79cddedf3cd436fb8d31af22600.tar.bz2
markdown-566b4ed42c6df79cddedf3cd436fb8d31af22600.zip
Fixed #61. stdin and stdout should work better in python 3.
Apparently, in Python3 stdin and stdout take str (unicode) not bytes. This provides a solution that will work in both python 2 & 3.
Diffstat (limited to 'markdown/__init__.py')
-rw-r--r--markdown/__init__.py40
1 files changed, 25 insertions, 15 deletions
diff --git a/markdown/__init__.py b/markdown/__init__.py
index 5764c60..0a27475 100644
--- a/markdown/__init__.py
+++ b/markdown/__init__.py
@@ -333,28 +333,38 @@ class Markdown:
encoding = encoding or "utf-8"
# Read the source
- if isinstance(input, basestring):
- input_file = codecs.open(input, mode="r", encoding=encoding)
+ if input:
+ if isinstance(input, str):
+ input_file = codecs.open(input, mode="r", encoding=encoding)
+ else:
+ input_file = codecs.getreader(encoding)(input)
+ text = input_file.read()
+ input_file.close()
else:
- input = input or sys.stdin
- input_file = codecs.getreader(encoding)(input)
- text = input_file.read()
- input_file.close()
- text = text.lstrip(u'\ufeff') # remove the byte-order mark
+ text = sys.stdin.read()
+ if not isinstance(text, unicode):
+ text = text.decode(encoding)
+
+ text = text.lstrip('\ufeff') # remove the byte-order mark
# Convert
html = self.convert(text)
# Write to file or stdout
- if isinstance(output, basestring):
- output_file = codecs.open(output, "w",
- encoding=encoding,
- errors="xmlcharrefreplace")
- output_file.write(html)
- output_file.close()
+ if output:
+ if isinstance(output, str):
+ output_file = codecs.open(output, "w",
+ encoding=encoding,
+ errors="xmlcharrefreplace")
+ output_file.write(html)
+ output_file.close()
+ else:
+ writer = codecs.getwriter(encoding)
+ output_file = writer(output, errors="xmlcharrefreplace")
+ output_file.write(html)
+ # Don't close here. User may want to write more.
else:
- output = output or sys.stdout
- output.write(html.encode(encoding, "xmlcharrefreplace"))
+ sys.stdout.write(html)
return self