From 54a4ae7146dc653f5ac78f41ad4f1eb1de48cf0e Mon Sep 17 00:00:00 2001 From: Stephen L Arnold Date: Sun, 8 Nov 2020 16:28:44 -0800 Subject: [PATCH] pystache/common.py: test failures in Windows due to CRs * cleaned up from https://github.com/defunkt/pystache/pull/193 Signed-off-by: Stephen L Arnold --- pystache/common.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/pystache/common.py b/pystache/common.py index fb266dd..0cfb5df 100644 --- a/pystache/common.py +++ b/pystache/common.py @@ -39,18 +39,24 @@ def read(path): Return the contents of a text file as a byte string. """ + import platform # Opening in binary mode is necessary for compatibility across Python # 2 and 3. In both Python 2 and 3, open() defaults to opening files in # text mode. However, in Python 2, open() returns file objects whose # read() method returns byte strings (strings of type `str` in Python 2), # whereas in Python 3, the file object returns unicode strings (strings # of type `str` in Python 3). - f = open(path, 'rb') - # We avoid use of the with keyword for Python 2.4 support. - try: - return f.read() - finally: - f.close() + file_mode = 'r' + code_page = 'utf-8' + if version_info < (3, ): + file_mode = 'rbU' + if platform.system() == "Windows": + code_page = 'utf-16' + + with open(path, file_mode) as f: + if version_info < (3, ): + return f.read() + return f.read().encode(code_page) class MissingTags(object):