From 566b4ed42c6df79cddedf3cd436fb8d31af22600 Mon Sep 17 00:00:00 2001 From: Waylan Limberg Date: Wed, 28 Dec 2011 15:59:47 -0500 Subject: 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. --- markdown/__init__.py | 40 +++++++++++++++++++++++++--------------- markdown/__main__.py | 2 +- 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] -- cgit v1.2.3