aboutsummaryrefslogtreecommitdiffstats
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
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.
-rw-r--r--markdown/__init__.py40
-rw-r--r--markdown/__main__.py2
2 files changed, 26 insertions, 16 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
diff --git a/markdown/__main__.py b/markdown/__main__.py
index 56afc10..b6a2e23 100644
--- a/markdown/__main__.py
+++ b/markdown/__main__.py
@@ -53,7 +53,7 @@ def parse_options():
(options, args) = parser.parse_args()
if len(args) == 0:
- input_file = sys.stdin
+ input_file = None
else:
input_file = args[0]