aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorWaylan Limberg <waylan@gmail.com>2011-12-29 04:59:47 +0800
committerMike Dirolf <mike@dirolf.com>2012-01-15 00:45:37 +0800
commitf3959302ef1ffa5ea3811a92ef97903320331020 (patch)
treec90dfcbcb17272204a9daf26e8776d46a31bd29d
parent35930e0928e19e37f81c906d5d11dfcc1087092b (diff)
downloadmarkdown-f3959302ef1ffa5ea3811a92ef97903320331020.tar.gz
markdown-f3959302ef1ffa5ea3811a92ef97903320331020.tar.bz2
markdown-f3959302ef1ffa5ea3811a92ef97903320331020.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]